首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于DataFrame的条形图线段的正确标注

基于DataFrame的条形图线段的正确标注
EN

Stack Overflow用户
提问于 2019-10-31 22:19:18
回答 1查看 73关注 0票数 0

我画了一个堆叠的条形图(请看这里:https://imgur.com/a/ESJeHuF),由下面的数据框组成。

代码语言:javascript
复制
                            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轴上有时间戳,并且每个条件的条形图的分段应该有正确的颜色。

代码语言:javascript
复制
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)

如果您能帮忙,我将不胜感激,提前谢谢您。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-01 01:34:15

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

代码语言:javascript
复制
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())])

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58645313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档