Python 基于值的颜色 matplotlib 条形图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33476401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:25:13  来源:igfitidea点击:

Color matplotlib bar chart based on value

pythonmatplotlib

提问by darkpool

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. 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).

谢谢 kikocorreoso 的建议。根据您的示例,当两个轴都是数字时,这很有效。但是在我的情况下,我的原始数据结构是一个熊猫数据框。然后我使用 df.stack() 并绘制结果。这意味着数据框行/列成为绘图的 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. eg:

我已经尝试按照您的示例进行屏蔽,但是当 Y 轴是数字而 X 轴是名称时,它似乎不起作用。例如:

     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. Each cell value will be a bar. And ultimately, coloring the bars as per the original question. Thanks

需要将上述数据框绘制为条形图,其中行/列组合形成 x 轴。每个单元格值将是一个条形。最后,根据原始问题为条形着色。谢谢

采纳答案by kikocorreoso

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()

The result should be: enter image description here

结果应该是: 在此处输入图片说明

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:

代码简要说明:

  • 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 dfstackeddataframe has a MultiIndexthe ticks are not well printed so I use the rotkeyword to rotate them. If you want to automate it in order to get a nice plot you can use plt.tight_layout()before plt.show().
  • 我为我的红柱创建了一个蒙版
  • 我创建了一系列颜色
  • 更改颜色数组以便为我的蒙版值使用其他颜色
  • 由于dfstacked数据框有一个MultiIndex刻度没有很好地打印,所以我使用rot关键字来旋转它们。如果你想自动化它以获得一个漂亮的图,你可以使用plt.tight_layout()before plt.show()

I hope it helps.

我希望它有帮助。