Search code examples
python-3.xmatplotlibdata-visualization

Align the values on the bar in matplotlib barplot


I am trying to obtain a bar chart displaying value_counts() for each year.

I use the following code:

import matplotlib.pyplot as plt

df.Year.value_counts(sort=False).sort_index().plot(kind='barh')

for index, value in enumerate(df['Year'].value_counts()):
    plt.text(value, index,
         str(value))

plt.show()

The chart that I obtain is as follows:

My bar chart

While it is correct, the issue is that all values are not aligned above the bars neatly and the alignment of values looks very haphazard. In short, they are not aesthetically pleasing.

Can someone please tell me how to fix this part (perhaps adding some height parameters in the code) so that all the values look neatly aligned on the bars.


Solution

  • While plotting, you are using sort_index() which sorts the bars based on year. But, this uses the sorted values for plotting. When you use the plt.text() the numbers are written based on the unsorted values. So, while the text values are in the correct location, the bars are not.

    If you provide the data used, can provide the updates. But, I am using the data based on the plot and working backwards here. Note that I am NOT using value_counts(), but plotting with just the values in the sample below. See if this helps...

    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({'Year': [2019,2020,2021,2022], 'Value':[275,237,235,170]})
    df.set_index(['Year'], inplace=True)
    df.sort_index(inplace=True)
    print(df)
    df.Value.plot(kind='barh')
    for index, value in enumerate(df['Value']):
        plt.text(value, index, str(value))
    plt.show()
    

    Output

    >>  df
          Value
    Year       
    2019    275
    2020    237
    2021    235
    2022    170
    

    enter image description here