python条形图分组颜色_使用matplotlib的不同排序颜色的堆叠条形图

1586010002-jmsa.png

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']]

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.

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.

yO6FE.png

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

the result figure is:

0uRNS.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值