如何在matplotlib中交替堆积条形图的颜色?

1 投票
1 回答
5977 浏览
提问于 2025-04-16 02:22

我想在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都是我需要在同一个图中绘制的数据列表,而我还有一个类型列表,用来标识上面提到的每个列表中的元素。我只想知道,如何才能根据类型列表中的类型来改变图表的颜色,同时又能把所有的条形图放在一个图中。

1 个回答

5

我有点困惑,你说 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)

撰写回答