[英]How to change bar color based on number value in matplotlib
I have a horizontal bar chart where I'm supposed to turn the bars slowly from yellow to red based on the horizontal value.我有一个水平条形图,我应该根据水平值将条形慢慢从黄色变为红色。 So the greater the X value the more the bars chart get red
所以 X 值越大,条形图越红
(I wanted to show the plot but I couldn't upload the image of it due to my low reputation) (我想展示 plot 但由于我的声誉低,我无法上传它的图像)
import matplotlib.pyplot as plt
x = [3,3,4]
y = [1,2,5]
plt.barh(x,y)
plt.show()
I'd do something of similar, hand-made:我会做一些类似的手工制作:
colorsValue = []
for value in x:
if value < LOW_TRESHOLD:
colorsValue.append('yellow')
elif value >= HIGH_TRESHOLD:
colorsValue.append('red')
else:
colorsValue.append('orange')
plt.barh(x, y, color = colorsValue)
where LOW_TRESHOLD
and HIGH_TRESHOLD
are values decided by you, as well as colors.其中
LOW_TRESHOLD
和HIGH_TRESHOLD
是您决定的值,还有 colors。 List of matplotlib colors is here . matplotlib colors 的列表在 这里。
This was only a minimal example to show you the syntax.这只是向您展示语法的一个最小示例。 Solution of Kroshtan is good as well and more general than my home-made solution, so I advice you to use his one.
Kroshtan 的解决方案也很好,比我自制的解决方案更通用,所以我建议你使用他的解决方案。
You can pass an array in the color
parameter.您可以在
color
参数中传递一个数组。 The values of this array can be calculated using cmap from the matplotlib documentation.可以使用 matplotlib 文档中的 cmap 计算此数组的值。
colors = [(1, 1, 0), (1, 0, 0)]
my_cmap = LinearSegmentedColormap.from_list(
'color_map', colors, N=100)
Then you scale the colors to the values you have:然后将 colors 缩放到您拥有的值:
rescale = lambda y: (y - np.min(y)) / (np.max(y) - np.min(y))
plt.barh(x,y,color=my_cmap(rescale(y)))
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.