【问题标题】:How do you annotate a chart from a pivot-table dataframe column?如何从数据透视表数据框列中注释图表?
【发布时间】:2017-12-07 03:42:17
【问题描述】:

我有一个数据集

a   b   c   d
10-Apr-86   Jimmy   1   this is
11-Apr-86   Minnie  2   the way
12-Apr-86   Jimmy   3   the world
13-Apr-86   Minnie  4   ends
14-Apr-86   Jimmy   5   this is the
15-Apr-86   Eliot   6   way
16-Apr-86   Jimmy   7   the world ends
17-Apr-86   Eliot   8   not with a bang
18-Apr-86   Minnie  9   but a whimper

我想在 matplotlib 中制作一个看起来像这样的图表

我已经弄清楚如何使用以下代码仅获取点(无​​注释):

df = (pd.read_csv('python.csv'))
df_wanted = pd.pivot_table(
    df,
    index='a',
    columns='b',
    values='c')

df_wanted.index = pd.to_datetime(df_wanted.index)

plt.scatter(df_wanted.index, df_wanted['Jimmy'])
plt.scatter(df_wanted.index,df_wanted['Minnie'])
plt.scatter(df_wanted.index,df_wanted['Eliot'])

我认为要进行注释,我需要在我的数据透视表的最后一列上列出一个值列表(如 here 所示)

我的问题是:如何让原始数据集的最后一列“d”成为我的数据透视表的最后一列?

我尝试了dat1 = pd.concat([df_wanted, df['d']], axis = 1) - 但这在我的数据框行下方创建了一组新行。我意识到轴不一样,所以我尝试使用 d 列作为值创建一个新的数据透视表 - 但收到错误消息 No numeric types to aggregate

我尝试了df_wanted2.append(df['d']) - 但这为 d 列中的每个元素创建了一个新列。

有什么建议吗?最终,我想让它在鼠标滚过该点时出现数据标签

【问题讨论】:

    标签: python matplotlib dataframe


    【解决方案1】:

    在这种特定情况下,您似乎不需要将 d 列设置为数据透视表的最后一列。

    plt.scatter(df_wanted.index, df_wanted['Jimmy'])
    plt.scatter(df_wanted.index,df_wanted['Minnie'])
    plt.scatter(df_wanted.index,df_wanted['Eliot'])
    plt.legend(loc=0)
    
    for k, v in df.set_index('a').iterrows():
        plt.text(k, v['c'], v['d']) # or: plt.annotate(xy=(k, v['c']), s=v['d'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-18
      • 2018-10-28
      • 2017-10-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多