【问题标题】:Pandas colormap with groupby带有 groupby 的 Pandas 颜色图
【发布时间】:2013-12-07 02:13:47
【问题描述】:

pandas 和 matplotlib 的新手,在使用 groupby 时无法使颜色图正常工作。

这是我的测试;

x=[]
for i in range(5):
   for j in range(9):
        x.append({'time':datetime(2013,1,1+i), 'col1':chr(ord('A')+j), 'col2':chr(ord('Z')-j), 'value':100+i*j})
df=pd.DataFrame(x)
df=df.set_index('time')
df

构建此数据集;

col1 col2 值 时间 2013-01-01 AZ 100 2013-01-01 B Y 100 2013-01-01 C X 100 2013-01-01 D W 100 2013-01-01 电动汽车 100 2013-01-01 F U 100 2013-01-01 G T 100 2013-01-01 H S 100 2013-01-01 I R 100 2013-01-02 AZ 100 2013-01-02 B Y 101 2013-01-02 C X 102 2013-01-02 D W 103 2013-01-02 EV 104 2013-01-02 F U 105 2013-01-02 G T 106 2013-01-02 H S 107 2013-01-02 I R 108 2013-01-03 AZ 100 2013-01-03 B Y 102 2013-01-03 C X 104 2013-01-03 D W 106 2013-01-03 EV 108 2013-01-03 F U 110 2013-01-03 G T 112 2013-01-03 H S 114 2013-01-03 I R 116 2013-01-04 AZ 100 2013-01-04 B Y 103 2013-01-04 C X 106 2013-01-04 D W 109 2013-01-04 EV 112 2013-01-04 F U 115 2013-01-04 G T 118 2013-01-04 H S 121 2013-01-04 I R 124 2013-01-05 AZ 100 2013-01-05 B Y 104 2013-01-05 C X 108 2013-01-05 D W 112 2013-01-05 EV 116 2013-01-05 F U 120 2013-01-05 G T 124 2013-01-05 H S 128 2013-01-05 I R 132

如果我正常绘制,最后几项颜色相同;

df.groupby(['col1','col2'])['value'].plot()
plt.legend()

http://postimg.org/image/cta2pa76f/

如果我尝试使用颜色图,它似乎不起作用;

df.groupby(['col1','col2'])['value'].plot(colormap='jet')
plt.legend()

http://postimg.org/image/8y6ompo0n/

如果我尝试'Blues',白色背景上的所有白线会更糟。

任何帮助表示赞赏!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    它确实有效,但是因为您是从GroupBy 绘制的,所以每个组(包含 1 列)被逐个绘制,但在相同的轴上。此单列从选定的colormap 中获取第一种颜色。

    要使颜色图起作用,您需要多个列,然后每列从颜色图中获得不同的颜色。

    您可以将 'col1' 和 'col2' 移动到索引中,然后将它们拆开。这假设每个时间戳只有一个 (col1, col2) 组合。对于你原来的df

    df.set_index(['col1', 'col2'], append=True, inplace=True)
    df.unstack(['col1', 'col2']).xs('value', axis=1).plot(colormap='jet')
    

    或者,您可以使用您选择的颜色图修改 Matplotlibs color cycle。然后您的第一个绘图将从颜色图中获取颜色。看: http://matplotlib.org/1.2.1/examples/api/color_cycle.html

    编辑:

    使用pivot 可能比如上所示的unstacking 更合适:

    df = pd.pivot_table(df.reset_index(),values='value', 
                        rows=['time'],cols=['col1', 'col2'])
    
    df.plot(colormap='jet')
    

    【讨论】:

    • 我还发现使用可选参数 fill_value=0 很有用,这样可以绘制缺失的行。
    猜你喜欢
    • 2015-07-04
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2021-04-30
    相关资源
    最近更新 更多