【问题标题】:Plot graph using Pandas - Plot 3 column data in a graph使用 Pandas 绘制图表 - 在图表中绘制 3 列数据
【发布时间】:2020-11-10 01:14:50
【问题描述】:

我的数据框中的数据为 df,包含 3 列(CODE、AGE、COUNT)

import pandas as pd

data = {'CODE': ['A', 'B', 'N', 'k', 'A', 'A', 'Z', 'L', 'O', 'B', 'Z'],
        'AGE': [1, 2, 3, 4, 5, 6, 40, 42, 48, 65, 65],
        'COUNT': [1800, 4000, 2000, 6500, 3500, 5000, 4, 10, 10, 8, 8]}

df = pd.DataFrame(df)

我需要将数据绘制为条形图,X 轴为 AGE,Y 轴为 COUNT。还需要在图中的每个条形图的顶部标记 A、B、N、Z 等代码。我们如何在 pandas 的每个条中提及 CODE?

【问题讨论】:

    标签: pandas dataframe matplotlib plot graph


    【解决方案1】:

    IIUC,你想要这样的东西:

    ax = df.plot.bar(x='AGE', y='COUNT', logy=True)
    for n, i in enumerate(ax.patches):
         ax.annotate(df.iloc[n, df.columns.get_loc('CODE')], (i.get_x() + i.get_width() / 2., i.get_height()),
         ha='center', va='center', fontsize=11, color='black', xytext=(0, 5),
         textcoords='offset points')
    #Make space for labels
    _ = ax.set_ylim(0, df['COUNT'].max()+10000)
    

    输出:

    【讨论】:

    • @FayasKY 这个解决方案对您有帮助吗?
    猜你喜欢
    • 2021-11-24
    • 2019-12-12
    • 1970-01-01
    • 2012-03-06
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多