使用matplotlib的不同排序颜色的堆叠条形图 [英] Stacked bar chart with differently ordered colors using matplotlib
问题描述
我是python的乞丐。我试图做一个水平barchart不同排序的颜色。
I am a begginer of python. I am trying to make a horizontal barchart with differently ordered colors.
我有一个数据集,如下所示:
I have a data set like the one in the below:
dataset = [{'A':19, 'B':39, 'C':61, 'D':70},
{'A':34, 'B':68, 'C':32, 'D':38},
{'A':35, 'B':45, 'C':66, 'D':50},
{'A':23, 'B':23, 'C':21, 'D':16}]
data_orders = [['A', 'B', 'C', 'D'],
['B', 'A', 'C', 'D'],
['A', 'B', 'D', 'C'],
['B', 'A', 'C', 'D']]
第一个列表包含数字数据,一个包含每个数据项的顺序。我需要第二个列表在这里,因为A,B,C和D的顺序是至关重要的数据集时呈现在我的情况下。
The first list contains numerical data, and the second one contains the order of each data item. I need the second list here, because the order of A, B, C, and D is crucial for the dataset when presenting them in my case.
使用数据像上面,我想做一个堆叠的条形图如下图所示。它是用MS Excel由我手动。我现在希望做的是使这种类型的条形图使用Matplotlib与像上面的数据集更自动的方式。如果可能,我还想向图表添加图例。
Using data like the above, I want to make a stacked bar chart like the picture in the below. It was made with MS Excel by me manually. What I hope to do now is to make this type of bar chart using Matplotlib with the dataset like the above one in a more automatic way. I also want to add a legend to the chart if possible.
实际上,我自己完全失去了尝试。任何帮助将是非常,非常有益的。
非常感谢您的关注!
Actually, I have totally got lost in trying this by myself. Any help will be very, very helpful. Thank you very much for your attention!
推荐答案
这是一个长程序,但它工作,我添加了一个伪数据来区分行计数和列计数:
It's a long program, but it works, I added one dummy data to distinguish rows count and columns count:
import numpy as np
from matplotlib import pyplot as plt
dataset = [{'A':19, 'B':39, 'C':61, 'D':70},
{'A':34, 'B':68, 'C':32, 'D':38},
{'A':35, 'B':45, 'C':66, 'D':50},
{'A':23, 'B':23, 'C':21, 'D':16},
{'A':35, 'B':45, 'C':66, 'D':50}]
data_orders = [['A', 'B', 'C', 'D'],
['B', 'A', 'C', 'D'],
['A', 'B', 'D', 'C'],
['B', 'A', 'C', 'D'],
['A', 'B', 'C', 'D']]
colors = ["r","g","b","y"]
names = sorted(dataset[0].keys())
values = np.array([[data[name] for name in order] for data,order in zip(dataset, data_orders)])
lefts = np.insert(np.cumsum(values, axis=1),0,0, axis=1)[:, :-1]
orders = np.array(data_orders)
bottoms = np.arange(len(data_orders))
for name, color in zip(names, colors):
idx = np.where(orders == name)
value = values[idx]
left = lefts[idx]
plt.bar(left=left, height=0.8, width=value, bottom=bottoms,
color=color, orientation="horizontal", label=name)
plt.yticks(bottoms+0.4, ["data %d" % (t+1) for t in bottoms])
plt.legend(loc="best", bbox_to_anchor=(1.0, 1.00))
plt.subplots_adjust(right=0.85)
plt.show()
结果数字是:
>
这篇关于使用matplotlib的不同排序颜色的堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!