Home > Software engineering >  How to show values above the bar Python
How to show values above the bar Python

Time:01-27

I have a very simple DataFrame, and I want to apply a goupby so I can plot the common count between the two columns.

Then I want to plot the grouped DataFrame.

I did it by the following lines of codes:

my_data = {
    "source": ['Live','Twitter','Twitter','Telegram','Telegram'],
    "second_source":['Qa','Unspecified','Da','Hzo','Tolib'],
    "count":[7,1,1,1,1]
}
my_dataframe = pd.DataFrame(my_data)

# Make the dataframe goupedby for the first two columns
# Then plot the count for them both
grouped_dataframe = my_dataframe.groupby(['source', 'second_source']).agg('sum')

grouped_dataframe.plot(kind='bar', figsize=(10,5))
plt.xticks(rotation=40, ha='right')
plt.title("Sources")
plt.show()

Output:

Output Image

How can I show the count numbers above every bar in the plot?

CodePudding user response:

Modify your code to:

ax = grouped_dataframe.plot(kind='bar', figsize=(10,5))

for x, val in enumerate(grouped_dataframe['count']):
    ax.text(x, val, val, va='bottom', ha='center')

enter image description here

  • Related