![](/img/trans.png)
[英]How to plot stacked bars within grouped bars within further grouped bars in a bar-chart using Python (or R)
[英]How to (iteratively) write a string alongside the bars of a grouped bar plot in Python?
我使用 Python 编写了一个水平分组条形图。 我的要求是我想在条形旁边写下与每个条形相关的数字。 我在网上看到过类似的问题。 但是我不确定如何在有分组条的特定情况下执行任务。 以下是我的代码:
# 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')
此处添加所需的更新。 请注意,我增加了图形大小,以便您可以看到数字并将图例框移到绘图之外。 至少有一部分解决方案在这里可用。 如果您有较新版本的 matplotlib(3.4.2 或更高版本),您还可以使用bar_label
功能
# 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')
输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.