Search code examples
pythonpandasmatplotlibanalysis

How do I set a row as x axis in matplotlib bar chart?


I want to have the x axis as the years, the y axis as the number of crime and i am looking to do this for each crime.

Any help would be much appreciated.

enter image description here


Solution

  • I've included the xticks as years and yaxis as total count of crimes which is present in your first row. Have a look on this and tell me what else you need.

    import pandas as pd
    import matplotlib.pyplot as plt
    
    # Creating a dummy dataframe
    df = pd.DataFrame({'Offense':['Total violence', 'Attempted Murder', 'Harrasment'],
                       '01/2018':[23, 21, 2],
                      '05/2018':[140, 80, 60]})
    df
    #   01/2018 05/2018 Offense
    # 0 23      140     Total violence
    # 1 21      80      Attempted Murder
    # 2 2       60      Harassment
    
    plt.bar(np.arange(2), df.iloc[0,:2])
    plt.xticks(np.arange(2), df.columns[:2])
    plt.show()
    

    plt1