Matplotlib:将背景色图与熊猫的列值匹配

问题描述 投票:0回答:1

我有一个数据框(x,y,颜色),每当“颜色”更改值时,我都试图更改背景颜色。到目前为止,我的结果具有背景色偏移量:Results so far

我希望图像的颜色与颜色值的变化对齐

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

           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个回答
0
投票

不理想,但这可行。

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])      

plt.xticks(df['x'][::2])
plt.xlim([df['x'].min(), df['x'].max()])
#DRAWING EXPECTED LINES 

plt.grid()

ax.axvline(x=6)
ax.axvline(x=11)
ax.axvline(x=16)
ax.axvline(x=22)
ax.axvline(x=27)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.