使用matplotlib不同颜色排列堆积柱形图(Stacked bar chart with dif

2019-07-30 05:01发布

我是一个Python的初学者。 我试图与不同的颜色排列的水平条形图。

我有一个数据集就像一个在下面:

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的顺序为数据集是至关重要的。

使用如上面的数据,我想使堆积条形图等在下面的图片。 它与MS Excel的由我手动进行。 我现在希望做的是使这种类型的使用Matplotlib与像上面一个更自动的方式在数据集条形图。 我也想,如果可能的传说添加到图表。

其实,我已经完全沉迷在我自己尝试这个。 任何帮助将是非常,非常有帮助。 非常感谢您的关注!

Answer 1:

这是一个漫长的程序,但它的作品,我加了一个虚拟的数据来区分行数和列数:

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()

结果数字是:



Answer 2:

>>> 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']]
>>> for i,x in enumerate(data_orders):
     for y in x:
        #do something here with dataset[i][y]  in matplotlib


文章来源: Stacked bar chart with differently ordered colors using matplotlib