【问题标题】:How to change histogram color based on x-axis in matplotlib如何在 matplotlib 中根据 x 轴更改直方图颜色
【发布时间】:2022-01-09 02:48:35
【问题描述】:

我有这个从熊猫数据框计算出来的直方图。

我想根据 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 轴。

【问题讨论】:

    标签: python pandas matplotlib histogram


    【解决方案1】:

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

    • get_x 返回左边缘,所以通过添加一半 get_width 得到中点
    • x 可能不会完全为 0,因此请使用一些缓冲区(本例中为 0.2)进行测试

    既然你asked for pandas in the comments,这个例子使用DataFrame.plot.hist,但你可以用任何基于matplotlib的直方图/条形图来做到这一点:

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

    【讨论】:

      【解决方案2】:

      一张一张地画出来:

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

      【讨论】:

      • 我想根据 x 轴上的值改变颜色。
      • @roger 这是根据 x 轴更改的 color = cmap(norm(np.abs(x0*10)))
      • @Z li 你能解释一下代码中发生了什么吗?当我将我的数据插入整个事情时,它会变成绿色?就像一个绿色的正方形。
      • 颜色由颜色图cmap 确定,并标准化为[0, 10] 的范围。在颜色部分,我相应地设置了x0 给出的颜色。因为这里x0 的值很小(-1 到 1),所以我将它乘以 10。如果你得到全绿色,可能是因为你的 x 值太小(小值变绿,大值变红)跨度>
      • 另外,如果你得到一个很大的正方形,那可能是因为你将条形的width 设置得太大了
      猜你喜欢
      • 2010-12-31
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2017-06-29
      • 1970-01-01
      相关资源
      最近更新 更多