我画了一个堆叠的条形图(请看这里: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轴上有时间戳,并且每个条件的条形图的分段应该有正确的颜色。
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)如果您能帮忙,我将不胜感激,提前谢谢您。
发布于 2019-11-01 01:34:15
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())])

https://stackoverflow.com/questions/58645313
复制相似问题