【发布时间】: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