I have coded a horizontal grouped bar plot using Python. My requirement is that I want to write the number associated with each bar alongside the bars. I have seen problems similar to this on the internet. But I am not sure how to carry out the task in my specific case where there are grouped bars. The following is my code:
# 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,
title='Grouped Bar Graph with dataframe')
The updates required is added here. Note that I have increased the figure size so you can see the numbers and moved the legend box outside the plot. At least a part of the solution is available here . If you have the newer version of matplotlib (3.4.2 or later), you can also use the bar_label
feature
# 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, figsize=(10,7), log = True,
title='Grouped Bar Graph with dataframe')
# Move legend outside the graph
ax.legend(bbox_to_anchor=(1.01, 1))
# Add labels
for p in ax.patches:
ax.annotate(str(p.get_width()), (p.get_x() + p.get_width(), p.get_y()-0.075), xytext=(5, 10), textcoords='offset points')
Output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.