【问题标题】:Matplotlib Annotate using values from DataFrameMatplotlib 使用 DataFrame 中的值进行注释
【发布时间】:2020-04-27 01:21:33
【问题描述】:

我正在尝试注释图表以包含 x 轴的绘制值以及来自 DataFrame 的其他信息。我能够注释 x 轴的值,但不确定如何从数据框中添加其他信息。在下面的示例中,我注释了 x 轴,它们是 Completion 列中的值,但还想添加 CompletedParticipants 值从数据帧。

例如 Running Completion 是 20%,但我希望我的注释显示 CompletedParticipants格式中的值 - 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


    【解决方案1】:

    当您注释时,也循环通过列 CompletedParticipants

    for (c,p), i in zip(df[["Completed","Participants"]].values, ax.patches):
        ax.text(i.get_width() + .4,
                i.get_y() + .67,
                str(round((i.get_width()), 2)) + '%' + f" ({c}/{p})", fontsize=10)
    

    【讨论】:

    • 这太棒了。这完成了我一直在寻找的东西。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2018-08-20
    相关资源
    最近更新 更多