[英]Color matplotlib bar chart based on value
Is there a way to color the bars of a barchart based on the bar's value.有没有办法根据条形图的值为条形图的条形着色。 For example:
例如:
- values below -0.5: red
- values between -0.5 to 0: green
- values between 0 to 08: blue
- etc
I have found some basic examples of bar coloring but nothing which can cater for value ranges, such as the above examples.我发现了一些条形着色的基本示例,但没有任何可以满足值范围的示例,例如上面的示例。
UPDATE:更新:
Thank you kikocorreoso for your suggestion.谢谢 kikocorreoso 的建议。 This works great when both axes are numbers as per your example.
根据您的示例,当两个轴都是数字时,这很有效。 However in my case my original data structure is a pandas dataframe.
但是在我的情况下,我的原始数据结构是一个熊猫数据框。 I then use df.stack() and plot the result.
然后我使用 df.stack() 并绘制结果。 This means that the dataframes rows/columns become the x axis of the plot and the dataframe cells are the Y axis (bars).
这意味着数据框行/列成为绘图的 x 轴,数据框单元格是 Y 轴(条形)。
I have tried masking as per your example but it doesn't seem to work when the Y axis are numbers and the X axis are names.我已经尝试按照您的示例进行屏蔽,但是当 Y 轴是数字而 X 轴是名称时,它似乎不起作用。 eg:
例如:
col1 col2 col3 col4
row1 1 2 3 4
row2 5 6 7 8
row3 9 10 11 12
row4 13 14 15 16
The above dataframe needs to be plotted as a barchart with the row/column combinations forming the x-axis.需要将上述数据框绘制为条形图,其中行/列组合形成 x 轴。 Each cell value will be a bar.
每个单元格值将是一个条形。 And ultimately, coloring the bars as per the original question.
最后,根据原始问题为条形着色。 Thanks
谢谢
You could use masks for your datasets.您可以为数据集使用掩码。 A basic example could be the following:
一个基本示例如下:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10) * 0.1
mask1 = y < 0.5
mask2 = y >= 0.5
plt.bar(x[mask1], y[mask1], color = 'red')
plt.bar(x[mask2], y[mask2], color = 'blue')
plt.show()
UPDATE:更新:
As you updated your question I update the code.当你更新你的问题时,我更新了代码。 For your simple case, and if I understood correctly, you could do the following (ugly) hack:
对于您的简单案例,如果我理解正确,您可以执行以下(丑陋的)hack:
import pandas as pd
df = pd.DataFrame({'col1':[1,2,3], 'col2':[4,5,6]},
index = ['row1','row2','row3'])
dfstacked = df.stack()
mask = dfstacked <= 3
colors = np.array(['b']*len(dfstacked))
colors[mask.values] = 'r'
dfstacked.plot(kind = 'bar', rot = 45, color = colors)
plt.show()
Or use a more OO solution .或者使用更面向对象的解决方案。
The code briefly explained:代码简要说明:
dfstacked
dataframe has a MultiIndex
the ticks are not well printed so I use the rot
keyword to rotate them.dfstacked
数据帧有一个MultiIndex
,刻度没有很好地打印,所以我使用rot
关键字来旋转它们。 If you want to automate it in order to get a nice plot you can use plt.tight_layout()
before plt.show()
.plt.tight_layout()
之前使用plt.show()
。 I hope it helps.我希望它有帮助。
I see this question has been asked a long time ago already, but just in case it could help someone, this is what worked for me:我看到很久以前就有人问过这个问题,但以防万一它可以帮助某人,这对我有用:
Iterate over all values and append colors to a list depending on customized conditions, so you get a list with as many color specifications as you have values;迭代所有值并根据自定义条件将颜色附加到列表中,因此您将获得一个列表,该列表具有与您拥有的值一样多的颜色规范; then use the color list in
plt.bar()
:然后使用
plt.bar()
的颜色列表:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10) * 0.1
col = []
for val in y:
if val < 0.4:
col.append('blue')
elif val >= 0.7:
col.append('green')
else:
col.append('red')
# col looks like this: ['blue', 'blue', 'blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'green']
plt.bar(x, y, color = col)
small improvement to the answer above对上述答案的小改进
x = np.arange(4)
y = np.array([-2,3,-1,2])
cc=list(map(lambda x: 'red' if x <= 0 else 'blue', y))
plt.bar(x, y, color = cc)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.