python - Matplotlib:将背景颜色图与 pandas 列值匹配

标签 python pandas matplotlib colors

我有一个数据框(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()

最佳答案

不理想,但可行。

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

关于python - Matplotlib:将背景颜色图与 pandas 列值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218292/

相关文章:

python - Keras 可以像 tensorflow 数据集那样预取数据吗?

python - AWS : Unable to import module 'handler' : No module named 'numpy'

python - 计算具有多个数据帧的列表中的平均值的最快方法

python - 尝试使用 pip 安装 matplotlib 和 numpy 时出现错误

python - 对 pandas 数据帧列表上的函数进行向量化

python - 在 Python 中保存/加载列表

pandas - 如何查找包含列表的系列元素?

python - Pandas - 类别变量和分组依据 - 这是一个错误吗?

python - 在带有 Matplotlib 的 Python 中,如何检查图中的子图是否为空

python - matplotlib 中的实时绘图 - python