开发者

How to alternate colors in stacked bar graph in matplotlib?

开发者 https://www.devze.com 2023-01-10 04:04 出处:网络
I want to alternate colors in a stacked bar graph in matplotlib..so as I can get different colors for the graphs depending on their type. I have two types except that they do not alternate regularly.

I want to alternate colors in a stacked bar graph in matplotlib..so as I can get different colors for the graphs depending on their type. I have two types except that they do not alternate regularly. so I need to check their type before I choose the colors.

The problem is that it is conditional. I provide the type in an array, but there is no way to do it at the level of the plt.bar(.............)...well I think.

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

p2 = plt.bar(self.__ind开发者_JS百科,
                    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 and self.__b and self.__c are all data lists that I need to plot in the same figure and I have another list of types for each element of the mentioned lists above. I only want to know how could I make it possible to change the colors of the graphs depending on the type provided by the types list and at the same time keeping all the bars in one plot.


I'm confused when you say that self.__a is a list - when I try plotting a list:

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

I get

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

However, what you can do is plot your values in a loop:

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

精彩评论

暂无评论...
验证码 换一张
取 消