Home > OS >  Python: Displaying values alongside a bar in a bar graph. Values greater than the actual value is ge
Python: Displaying values alongside a bar in a bar graph. Values greater than the actual value is ge

Time:05-11

I am trying to plot a grouped bar graph in which I display the corresponding value alongside the bar. Currently, what my code does is, it displays the value alongside the bar, which is 1 greater than the actual value. What changes do I need to make in my code such that it displays the actual value alongside the bars?

enter image description here

# importing package
import matplotlib.pyplot as plt
import pandas as pd
  
# create data
df = pd.DataFrame([['A', 10, 20, 10, 30], ['B', 20, 25, 15, 25], ['C', 12, 15, 19, 6],
                   ['D', 10, 29, 13, 19]],
                  columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])
# view data
print(df)


  
# plot grouped bar chart
ax=df.plot.barh(x='Team',        
        stacked=False,
        log=True,
        figsize=(12, 7),
        title='Grouped Bar Graph with dataframe')

for c in ax.containers:     
    ax.bar_label(c, label_type='edge')

CodePudding user response:

If you look at the documentation help(ax.bar_label) it is hinted that label_type="edge" and label_type="center" shows different values. One way to fix that is to pass our labels, like this:

for c in ax.containers:
    labels = c.datavalues.astype(str)
    ax.bar_label(c, label_type='edge', labels=labels)
  • Related