Python:在条形图中的条形旁边显示值。显示大于实际值的值
Python: Displaying values alongside a bar in a bar graph. Values greater than the actual value is getting displayed
我正在尝试绘制一个分组条形图,在其中我在条形旁边显示相应的值。目前,我的代码所做的是,它在条形图旁边显示比实际值大 1 的值。我需要对我的代码进行哪些更改才能在条形图旁边显示实际值?
# 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')
如果您查看文档 help(ax.bar_label)
,会提示 label_type="edge"
和 label_type="center"
显示不同的值。解决这个问题的一种方法是传递我们的标签,如下所示:
for c in ax.containers:
labels = c.datavalues.astype(str)
ax.bar_label(c, label_type='edge', labels=labels)
我正在尝试绘制一个分组条形图,在其中我在条形旁边显示相应的值。目前,我的代码所做的是,它在条形图旁边显示比实际值大 1 的值。我需要对我的代码进行哪些更改才能在条形图旁边显示实际值?
# 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')
如果您查看文档 help(ax.bar_label)
,会提示 label_type="edge"
和 label_type="center"
显示不同的值。解决这个问题的一种方法是传递我们的标签,如下所示:
for c in ax.containers:
labels = c.datavalues.astype(str)
ax.bar_label(c, label_type='edge', labels=labels)