【发布时间】:2020-04-27 01:21:33
【问题描述】:
我正在尝试注释图表以包含 x 轴的绘制值以及来自 DataFrame 的其他信息。我能够注释 x 轴的值,但不确定如何从数据框中添加其他信息。在下面的示例中,我注释了 x 轴,它们是 Completion 列中的值,但还想添加 Completed 和 Participants 值从数据帧。
例如 Running Completion 是 20%,但我希望我的注释显示 Completed 和 Participants格式中的值 - 20% (2/10)。下面是可以重现我的场景以及当前和期望结果的示例代码。任何帮助表示赞赏。
代码:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mydict = {
'Event': ['Running', 'Swimming', 'Biking', 'Hiking'],
'Completed': [2, 4, 3, 7],
'Participants': [10, 20, 35, 10]}
df = pd.DataFrame(mydict).set_index('Event')
df = df.assign(Completion=(df.Completed/df.Participants) * 100)
print(df)
plt.subplots(figsize=(5, 3))
ax = sns.barplot(x=df.Completion, y=df.index, color="cyan", orient='h')
for i in ax.patches:
ax.text(i.get_width() + .4,
i.get_y() + .67,
str(round((i.get_width()), 2)) + '%', fontsize=10)
plt.tight_layout()
plt.show()
数据帧:
Completed Participants Completion
Event
Running 2 10 20.000000
Swimming 4 20 20.000000
Biking 3 35 8.571429
Hiking 7 10 70.000000
电流输出:
所需的输出:
【问题讨论】:
标签: python-3.x pandas matplotlib seaborn