【问题标题】:How can I set positive values to one color and negative values to another in matplotlib?如何在 matplotlib 中将正值设置为一种颜色,将负值设置为另一种颜色?
【发布时间】:2021-07-08 09:12:10
【问题描述】:

我有一个随机正负值的条形图。我想在条形图中将所有负值设置为蓝色,将所有正值设置为红色。 如何将负值变为蓝色,将正值变为红色?

这是我迄今为止尝试过的,但我得到一个错误:

rand = np.random.randint(-2, 2, (30))
time = np.arange(1,31,1)

plt.bar(time, rand)
plt.show()

if rand < 0:
    plt.bar(time, rand,'blue')
elif rand > 0:
    plt.bar(time, rand,'red')
    plt.show()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-110-2154dd329d10> in <module>
----> 1 if rand < 0:
      2     plt.bar(time, rand,'blue')
      3 elif rand > 0:
      4     plt.bar(time, rand,'red')
      5     plt.show()

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

    标签: python numpy matplotlib jupyter


    【解决方案1】:

    numpy 表达式rand &lt; 0 给出了一组 True 和 False 值。这不能用于if-test。在if-test 中,整个表达式必须为 True 或 False。

    但是,表达式rand &lt; 0 可以用作数组的索引,只选择数组中的那些索引:

    from matplotlib import pyplot as plt
    import numpy as np
    rand = np.random.randint(-2, 2, (30))
    time = np.arange(1, 31, 1)
    
    plt.bar(time[rand < 0], rand[rand < 0], color='tomato')
    plt.bar(time[rand > 0], rand[rand > 0], color='cornflowerblue')
    plt.axhline(0, color='grey', lw=0.5)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      了解np.where

      plt.bar(x, y, color=np.where(y>0, 'b', 'r'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-23
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多