使用matplotlib
创建百分比堆积柱状图的思路与堆积柱状图类似,只不过bottom
参数累计的不是数值而是百分比,因此,需要事先计算每组柱子的数值总和,进而求百分比。
未使用numpy版本
适用于少量数据,数据结构需要手动构造。
import matplotlib.pyplot as plt labels = ['G1', 'G2', 'G3', 'G4', 'G5'] first = [20, 34, 30, 35, 27] second = [25, 32, 34, 20, 25] third = [21, 31, 37, 21, 28] fourth = [26, 31, 35, 27, 21] data = [first, second, third, fourth] x = range(len(labels)) width = 0.35 # 将bottom_y元素都初始化为0 bottom_y = [0] * len(labels) # 计算每组柱子的总和,为计算百分比做准备 sums = [sum(i) for i in zip(first, second, third, fourth)] for i in data: # 计算每个柱子的高度,即百分比 y = [a/b for a, b in zip(i, sums)] plt.bar(x, y, width, bottom=bottom_y) # 计算bottom参数的位置 bottom_y = [(a+b) for a, b in zip(y, bottom_y)] plt.xticks(x, labels) plt.title('Percent stacked bar ') plt.show()
使用numpy版本
第一个版本的缺陷在于数据需要手动构造,而且计算稍微繁琐一些。
使用numpy便于处理规模比较大且已存储在文件中数据的数据,计算更简便。
import numpy as np import matplotlib.pyplot as plt labels = ['G1', 'G2', 'G3', 'G4', 'G5'] first = [20, 34, 30, 35, 27] second = [25, 32, 34, 20, 25] third = [21, 31, 37, 21, 28] fourth = [26, 31, 35, 27, 21] data = [first, second, third, fourth] x = range(len(labels)) width = 0.35 # 将bottom_y元素都初始化为0 bottom_y = np.zeros(len(labels)) data = np.array(data) # 按列计算计算每组柱子的总和,为计算百分比做准备 sums = np.sum(data, axis=0) for i in data: # 计算每个柱子的高度,即百分比 y = i / sums plt.bar(x, y, width, bottom=bottom_y) # 计算bottom参数的位置 bottom_y = y + bottom_y plt.xticks(x, labels) plt.title('Percent stacked bar ') plt.show()
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“matplotlib bar()实现百分比堆积柱状图”评论...
更新日志
2024年07月03日
2024年07月03日
- 杨钰莹.1995-因为有你【新时代】【WAV+CUE】
- 许慧欣.2006-谜【上华】【WAV+CUE】
- 绝区零珂蕾妲驱动盘怎么搭配 珂蕾妲驱动盘及词条选择攻略
- 绝区零强袭鸣徽有哪些 绝区零强袭鸣徽效果介绍
- 魔兽世界奥格瑞玛怎么去幽暗城 奥格瑞玛去幽暗城方法介绍
- 《间谍过家家日记大作战》成就攻略一览
- 完美的音乐品质-群星《红酒杯发烧酒廊情歌》2CD[WAV]
- 群星.2011《高雄国际Hi-End音响大展纪念发烧金碟》[WAV分轨]
- 康康1999-催泪[阿尔法][WAV+CUE]
- 和守望先锋太像?《星鸣特攻》开发商:我们与众不同
- 速通玩家有福了!夏季游戏速通大会正在火热进行中
- 《使命召唤》新处决动作曝光 或联动《死侍3》?
- 《陈百强出道35周年 文质翩翩》4CD[WAV+CUE][1.8GB]
- 邓丽君《思君集》3CD[WAV+CUE][1.2GB]
- 华语流行S.H.E《12CD》2001~2010[APE+CUE][3.7GB]