基于数据框中的值的颜色条形图

时间:2019-10-31 05:40:35

标签: python pandas dataframe matplotlib bar-chart

我绘制了一个堆积的条形图(请参见此处: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',并且对堆叠的条形图的所有分段重复该行为。

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

fig = plt.figure()
ax = fig.add_subplot(111)
df.plot.bar(stacked=True, rot=1, legend=False, ax=fig.gca(), colors=color_list)

非常感谢您的帮助,在此先感谢您。

1 个答案:

答案 0 :(得分:1)

我不知道选择颜色对您有多重要。 我刚刚找到了一个似乎可以解决您问题的解决方案,唯一的“但是”是,如果您接受一种可用的颜色模式,则开发会更容易。 Othewrise,如果您需要手工制作一个颜色图,则可以从matplotlib.colors中找到带有LinearSegmentedColormap的示例。

代码:

    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]   

    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

    fig = plt.figure()
    ax = fig.add_subplot(111)
    df.plot.bar(stacked=True, rot=1, legend=False, ax=fig.gca(), color=custom)

    plt.show()

显示:

enter image description here