首页 > 解决方案 > 基于 DataFrame 正确标记条形图段

问题描述

我绘制了一个堆积条形图(参见此处:https ://imgur.com/a/ESJeHuF ),由下面的数据框组成。

                            condition1       condition2      condition3
timestamp                                                
2019-10-30 01:41:43             1.0             4.0             0.0
2019-10-30 01:50:11             1.0             2.0             4.0
2019-10-30 01:50:59             1.0             2.0             4.0
2019-10-30 01:51:36             1.0             2.0             4.0
2019-10-30 01:52:27             1.0             3.0             4.0
2019-10-30 01:53:10             2.0             4.0             0.0
2019-10-31 02:25:14             5.0             0.0             0.0
2019-10-31 04:15:54             5.0             0.0             0.0

我希望条形图中的颜色通过此颜色列表与数据框中的相应值匹配:

color_list = ['r', 'g', 'b', 'm', 'k', 'k']

(例如,如果第二个到最后一个时间步的值为 5,则将堆积条形图的段着色为'k',并为堆积条形图列的所有段重复该行为。

下面的代码绘制了堆叠的条形图,但是颜色错误(上面的链接显示了这一点)。它仅将前三种颜色分配给所有值,其中 Dataframe 中有更多对应的颜色/值。正确的绘图应该在 x 轴上有时间戳,并且每个条件的条形段都有正确的颜色。

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
data_color = [0.,1.,2.,3.,4.,5.] #data range from conditions columns
data_color = [x / max(data_color) for x in data_color]   
print(data_color)
custom_map = plt.cm.get_cmap('Accent') #one of the color schemas stored
custom = custom_map(data_color)  #mapping the color info to the variable custom
print(custom)
fig = plt.figure()
ax = fig.add_subplot(111)
df.plot.bar(stacked=True, rot=1, legend=False, ax=fig.gca(), color=custom)

我将不胜感激任何帮助,在此先感谢您。

标签: pythonpandasdataframematplotlibbar-chart

解决方案


IIUC 您希望所有相同高度的条具有相同的颜色。我不确定是否可以使用颜色映射来完成,但您可以在创建绘图后手动为条形着色:

color_list = ['r', 'g', 'b', 'm', 'k', 'c']
plot = df.plot.bar(stacked=True, legend=False)
for bar in plot.patches:
    bar.set_color(color_list[int(bar.get_height())])

在此处输入图像描述


推荐阅读