【问题标题】:How to alternate colors in stacked bar graph in matplotlib?如何在 matplotlib 的堆积条形图中交替颜色?
【发布时间】:2011-03-25 20:27:40
【问题描述】:

我想在 matplotlib 中的堆叠条形图中交替颜色..以便我可以根据图表的类型获得不同的颜色。我有两种类型,只是它们不定期交替。所以我需要在选择颜色之前检查它们的类型。

问题在于它是有条件的。我在数组中提供了类型,但没有办法在 plt.bar(.............) 的级别上做到这一点......我认为。

p1 = plt.bar(self.__ind,
                    self.__a,
                    self.__width, 
                    color='#263F6A')

p2 = plt.bar(self.__ind,
                    self.__b,
                    self.__width, 
                    color='#3F9AC9',
                    bottom = self.__arch)

p3 = plt.bar(self.__ind,
                    self.__c,
                    self.__width, 
                    color='#76787A',
                    bottom = self.__a + self.__b)

self.__a 和 self.__b 和 self.__c 都是我需要在同一个图中绘制的数据列表,对于上面提到的列表的每个元素,我都有另一个类型列表。 我只想知道如何才能根据类型列表提供的类型更改图表的颜色,同时将所有条形图保持在一个图中。

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    当你说 self.__a 是一个列表时,我很困惑 - 当我尝试绘制一个列表时:

    In [19]: plt.bar(1,[1,2,3], 0.1, color='#ffcc00')
    

    我明白了

    AssertionError: incompatible sizes: argument 'height' must be length 1 or scalar
    

    但是,您可以做的是在循环中绘制您的值:

    # Setup code here...
    
    indices = [1,2,3,4]
    heights = [1.2, 2.2, 3.3, 4.4]
    widths = [0.1, 0.1, 0.2, 1]
    types = ['spam', 'rabbit', 'spam', 'grail']
    
    
    for index, height, width, type in zip(indices, heights, widths, types):
        if type == 'spam':
            plt.bar(index, height, width, color='#263F6A')
        elif type == 'rabbit':
            plt.bar(index, height, width, color='#3F9AC9', bottom = self.__arch)
        elif type == 'grail':
            plt.bar(index, height, width, color='#76787a', bottom = 3)
    

    【讨论】:

    • 不客气,请记住,您应该通过单击答案左侧的复选标记来标记已接受的答案 - 如果您认为答案有用,您也应该投票。
    猜你喜欢
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2016-10-24
    • 2018-01-17
    • 2019-11-28
    • 2013-02-18
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多