基于值的颜色matplotlib条形图 [英] 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.
更新:
谢谢kikocorreoso的建议.根据您的示例,当两个轴都是数字时,这非常有用.但是对于我来说,我的原始数据结构是pandas数据框.然后,我使用df.stack()并绘制结果.这意味着数据框的行/列成为图的x轴,数据框的单元格为Y轴(条形).
Thank you kikocorreoso for your suggestion. 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. This means that the dataframes rows/columns become the x axis of the plot and the dataframe cells are the Y axis (bars).
我已经按照您的示例尝试了遮罩,但是当Y轴为数字而X轴为名称时,它似乎不起作用.例如:
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. 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
以上数据框需要绘制为条形图,其中行/列组合形成x轴.每个单元格值将是一个条形图.最终,按照原始问题为条形着色.谢谢
The above dataframe needs to be plotted as a barchart with the row/column combinations forming the x-axis. 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()
结果应为:
更新:
在您更新问题时,我也会更新代码.对于您的简单情况,如果我理解正确,则可以进行以下(丑陋的)破解:
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:
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()
或者使用更多的 OO解决方案.
代码简要说明:
- 我为我的红色列创建一个蒙版
- 我创建了一个颜色数组
- 更改颜色数组,以便将其他颜色用于蒙版值
- 由于
dfstacked
数据帧具有MultiIndex
,因此刻度没有很好地打印出来,因此我使用rot
关键字来旋转它们.如果要使其自动化以获取良好的绘图,可以在plt.show()
之前使用plt.tight_layout()
.
- I create a mask for my red columns
- I create an array of colors
- Change the the array of colors in order to use other color for my masked values
- As the
dfstacked
dataframe has aMultiIndex
the ticks are not well printed so I use therot
keyword to rotate them. If you want to automate it in order to get a nice plot you can useplt.tight_layout()
beforeplt.show()
.
希望对您有帮助.
这篇关于基于值的颜色matplotlib条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!