简体   繁体   English

python matplotlib每第N个小节显示不同的颜色

[英]Python matplotlib different color every N-th bar

So i created the following matplotlib diagramm.This is what it looks atm: 所以我创建了以下matplotlib图表。这是atm的样子: 在此处输入图片说明

Is there any way to change the colors after every 5th bar? 每第5个小节之后是否有任何更改颜色的方法? Like bar 1-5 have same color, 6-10 have same color, .... Couldn't seem to find the answer. 就像小节1-5具有相同的颜色,小节6-10具有相同的颜色,....似乎找不到答案。 Cheers 干杯

Yes, there is, and it's pretty easy. 是的,有,这很容易。 Look at the following code: 看下面的代码:

from matplot import pyplot as plt
bars = plt.bars(xrange(20), xrange(20))
for item in bars[::5]:
    item.set_color('r')
plt.show()

The bars() method returns a list of objects, where you can set the color with the set_color() method. bars()方法返回对象列表,您可以在其中使用set_color()方法设置颜色。 You then take the list and iterate over it with a step width of 5. You can shift the position of the colored bars by passing a starting index, for example bars[2::5]. 然后,获取列表并以5的步长对其进行迭代。您可以通过传递起始索引来移动彩色条的位置,例如,bars [2 :: 5]。

This gives the following result: 得到以下结果: 在此处输入图片说明

Edit: To achieve that the color changes on every 5th bar, the code has to look like this: 编辑:要使颜色在每第5条上发生变化,代码必须看起来像这样:

from matplotlib import pyplot as plt
colors = ['r']*5 + ['b']*5 + ['g']*5
barlist = plt.bar(xrange(15), xrange(15))
for item, color in zip(barlist, colors):
     item.set_color(color)
plt.show()

Which gives: 这使:

在此处输入图片说明

You can set the color of the bars by supplying a list of colors to the bar plot. 您可以通过为条形图提供颜色列表来设置bar的颜色。

import matplotlib.pyplot as plt
import numpy as np

#generate some data
x = range(24)
y = np.abs(np.random.normal(2, 1, 24))

#generate color list. 
color = ["orange"]*5 + ["purple"]*5 + ["darkturquoise"]*5+ ["firebrick"]*5 + ["limegreen"]*4 
plt.bar(x,y, color = color, align="center")   

plt.xlim((-1,24))
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM