如何在 matplotlib 中基于 x 轴更改直方图颜色

How to change histogram color based on x-axis in matplotlib

我根据 pandas 数据框计算了这个直方图。

我想根据 x 轴值更改颜色。
例如:

If the value is = 0 the color should be green
If the value is > 0 the color should be red
If the value is < 0 the color should be yellow  

我只关心 x 轴。酒吧的高度对我来说并不重要。所有其他解决方案都是针对 y 轴的。

把它们一一画出来:

import matplotlib as mpl
import matplotlib.pyplot as plt

x = np.linspace(-1,1,10)
y = np.random.uniform(0,1,10)
width = 0.2
plt.figure(figsize = (12, 6))
cmap = mpl.cm.RdYlGn.reversed()
norm = mpl.colors.Normalize(vmin=0, vmax=10)
for x0, y0 in zip(x,y):
    plt.bar(x0, y0, width = width, color = cmap(norm(np.abs(x0*10))))

对于ax.containers[0]中的每个小节补丁,根据x位置使用set_color

  • get_x returns the left edge, so get the midpoint by adding half of get_width
  • x 可能不会 完全是 0,因此请使用一些缓冲区进行测试(本例中为 0.2)

因为你 , this example uses DataFrame.plot.hist,但你可以用任何基于 matplotlib 的 histogram/bar 绘图来做到这一点:

df = pd.DataFrame({'A': np.random.default_rng(222).uniform(-1, 1, 40)})
ax = df.plot.hist()

for bar in ax.containers[0]:
    # get x midpoint of bar
    x = bar.get_x() + 0.5 * bar.get_width()

    # set bar color based on x
    if x < -0.2:
        bar.set_color('orange')
    elif x > 0.2:
        bar.set_color('red')
    else:
        bar.set_color('green')