【问题标题】:How to get different colors in different columns using stack bar in python如何使用python中的堆栈栏在不同的列中获取不同的颜色
【发布时间】:2020-04-01 17:06:06
【问题描述】:

问题:- 如何使用 Matplotlib 或 Seaborn 在不同的堆叠条中获得替代颜色。 举例来说 - 我在一个情节中有 3 个堆叠的条形图。 第一个栏应该说绿色,蓝色,黄色 第二个堆栈栏应该有橙色、蓝色、红色 第三个堆栈栏应该有蓝色、紫色、红色。

我写了下面的代码,它给了我堆栈栏,但不是我上面解释的颜色组合。我得到了我不需要的所有 3 个具有相同颜色的堆栈条。

任何帮助..

测试图 3

import numpy as np
from matplotlib import pyplot as plt

num_set = [{'USA':914, 'GBR':70, 'IND':48},
           {'USA':770, 'GBR':67, 'IND':16},
           {'USA':282, 'GBR':20, 'IND':12}]

lan_guage    = [['USA','GBR','IND'], 
               ['GBR','IND','USA'], 
               ['IND','USA','GBR']] 
colors = ["r","g","b"]
names = sorted(num_set[0].keys())
values = np.array([[data[name] for name in order] for data,order in zip(num_set, lan_guage)])
lefts = np.insert(np.cumsum(values, axis=1),0,0, axis=1)[:, :-1]
orders = np.array(lan_guage)
bottoms = np.arange(len(lan_guage))

for name, color in zip(names, colors):
    idx = np.where(orders == name)
    value = values[idx]
    left = lefts[idx]
    plt.bar(left, height=0.8, width=value, bottom=bottoms, 
    color=color, orientation="horizontal", label=name)
plt.yticks(bottoms+0.4, ["Student-%d" % (t+1) for t in bottoms])

plt.legend(loc="best", bbox_to_anchor=(1.0, 1.00))
plt.subplots_adjust(right=0.75)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')

plt.show()

【问题讨论】:

    标签: bar-chart


    【解决方案1】:
    N = 3 # No of Countries
    top_sector = (914,300, 200) ## No of Investment in top sectors for C1/C2/C3
    second_sector = (770,200,100) ## No of Investment in 2nd highest sector for C1/C2/C3
    third_sector = (282,100,50) ## No of Investment in 3rd highest sector for C1/C2/C3
    ind = np.arange(N)
    width = 0.35
    
    ## p1 thru p5 are for 5 sectors.
    p1 = plt.bar(ind,top_sector,width,color=['green','grey','green'])
    p2 = plt.bar(ind,second_sector,width,color=['grey','green','purple'])
    p3 = plt.bar(ind,third_sector,width,color=['red','brown','brown'])
    p4 = plt.bar(ind,fourth_sector,width,color=['brown'])
    p5 = plt.bar(ind,fifth_sector,width,color=['purple'])
    
    plt.xlabel('Top 3 Countries for Investment')
    plt.ylabel('No of Investment (Count)')
    plt.title('No of Investment in top 3 sectors of top 3 countries')
    plt.xticks(ind,('USA' , 'GBR', 'IND'))
    plt.yticks(np.arange(0,1000,200))
    plt.legend((p1[0],p2[0],p3[0],p4[0],p5[0]),('Others',' Health', 'Entertainment', 'Cleantech / Semiconductors','News,Searching/Msg'))
    plt.show()[enter image description here][1]
    
    IMAGE :-
      [1]: https://i.stack.imgur.com/A9fsI.png
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      相关资源
      最近更新 更多