【问题标题】:Matplotlib: Match background color plot to pandas column valuesMatplotlib:将背景颜色图与熊猫列值匹配
【发布时间】:2020-02-01 17:21:37
【问题描述】:

我有一个数据框(x,y,颜色),我试图在“颜色”更改值时更改背景颜色。

到目前为止我的结果有背景颜色偏移:

我希望图像的颜色与颜色值的变化保持一致

这是我运行的数据框和代码:

           y     x  color
0   0.691409  1.0   0    
1   0.724816  2.0   0    
2   0.732036  3.0   0    
3   0.732959  4.0   0    
4   0.734869  5.0   1    
5   0.737061  6.0   2    
6   0.717381  7.0   2    
7   0.704016  8.0   2    
8   0.693450  9.0   2    
9   0.684942  10.0  2    
10  0.674619  11.0  3    
11  0.677481  12.0  3    
12  0.680656  13.0  3    
13  0.682392  14.0  3    
14  0.682875  15.0  3    
15  0.685440  16.0  4    
16  0.678730  17.0  4    
17  0.666658  18.0  4    
18  0.659457  19.0  4    
19  0.652272  20.0  4    
20  0.647092  21.0  4    
21  0.645269  22.0  5    
22  0.649014  23.0  5    
23  0.652543  24.0  5    
24  0.653829  25.0  5    
25  0.655604  26.0  5    
26  0.656557  27.0  6    
27  0.647886  28.0  6    
28  0.642036  29.0  6  

剧情:


fix, ax= plt.subplots()
ax.plot(df['x'], df['y'])
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              df['color'].values[np.newaxis],
              cmap='Set3', alpha=0.3), 
plt.xticks(df['x'][::2])
#DRAWING EXPECTED LINES 

ax.axvline(x=6)
ax.axvline(x=11)
ax.axvline(x=16)
ax.axvline(x=22)
ax.axvline(x=27)
plt.show()

【问题讨论】:

    标签: python pandas matplotlib colors


    【解决方案1】:

    不理想,但这可行。

    from matplotlib.patches import Patch
    
    fix, ax= plt.subplots()
    ax.plot(df['x'], df['y'])
    
    cmap = matplotlib.cm.get_cmap('Set3')
    for c in df['color'].unique():
        bounds = df[['x', 'color']].groupby('color').agg(['min', 'max']).loc[c]
        ax.axvspan(bounds.min(), bounds.max()+1, alpha=0.3, color=cmap.colors[c])
    
    legend = [Patch(facecolor=cmap.colors[c], label=c) for c in df['color'].unique()]
    ax.legend(handles=legend)             
    plt.xticks(df['x'][::2])
    plt.xlim([df['x'].min(), df['x'].max()])
    #DRAWING EXPECTED LINES 
    
    ax.axvline(x=6)
    ax.axvline(x=11)
    ax.axvline(x=16)
    ax.axvline(x=22)
    ax.axvline(x=27)
    plt.show()
    

    【讨论】:

    • 它可以工作,但会在边缘留下很多空白。可以添加带有颜色的图例吗?
    • 空白是什么意思? 1> 或 >29?我已经编辑了答案,以展示您如何在其中添加图例。
    猜你喜欢
    • 2014-06-01
    • 2021-09-30
    • 2015-03-29
    • 2020-08-31
    • 2014-07-09
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多