Matplotlib:将背景颜色打印与列值匹配

2024-03-29 06:00:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧(x,y,color),每当“color”改变值时,我都试图改变背景色。你知道吗

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

Results so far

我希望图像的颜色与颜色值的变化保持一致。你知道吗

下面是我运行的datafrane和代码:

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

Tags: 数据代码图像dfget颜色pltax
1条回答
网友
1楼 · 发布于 2024-03-29 06:00:43

不太理想,但这很管用。你知道吗

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

With legend

相关问题 更多 >