Python绘制百分比堆叠柱状图并填充图案
通过Python中的matplotlib绘制百分比堆叠柱状图,并为每一个类别设置不同的填充图案。主要原因是有些论文打印出是黑白色的,不同类别之间区分不明显,所以做了这种方案。
存在一个问题:不知道如何根据填充图案设置图例,本文中可谓“曲线救国”,将图例的颜色块设置为了白色,所以如果有人知道如何根据hatching设置图例可以讨论,原始的legend方法中是未提供该类参数的。
图形如下:
代码如下
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.ticker as mtick
from matplotlib.ticker import PercentFormatter
#设置填充的图案
marks = ["o","/","*","..","\\"]
labels = [i for i in range(2010, 2021)]
#数据
first = [42.85, 41.15,39.41,35.35,35.53,30.45,29.81,31.85,32.41,30.42,31.49]
second = [23.20,26.40,27.77,29.02,32.30,35.40,36.42,35.95,35.45,34.00,31.93]
third = [14.08,12.99,12.51,11.54,11.70,12.27,12.69,11.81,10.63,9.98,9.95]
fourth = [16.14,16.17,17.34,21.53,17.66,19.36,18.40,17.83,19.15,23.09,24.10]
others = [3.73,3.28,2.98,2.57,2.81,2.53,2.67,2.57,2.36,2.51,2.54]
data = [first, second, third, fourth, others]
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)
j = 0
figsize = 8,6
figure, ax = plt.subplots(figsize=figsize)
plt.rcParams["font.sans-serif"] = ["SimHei"]
for i in data:
y = i / sums
plt.bar(x, y, width, hatch=np.array(marks)[j], bottom=bottom_y, color="white", edgecolor="black")
bottom_y = y + bottom_y
plt.xticks(x, labels)
#plt.yticks(range(1), ylabel)
legend_labels = ["o legend1", "/ legend2", "* legend3", "· legend4",r"\ legend5"]
color = ["white", "white", "white", "white", "white"]
patches = [mpatches.Patch(color=color[h],label="{:s}".format(legend_labels[h])) for h in range(len(legend_labels))]
ax = plt.gca()
box = ax.get_position()
#纵轴设置为百分比
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
ax.legend(handles=patches,ncol=1, bbox_to_anchor=(1, 1), borderaxespad = 0.) # 生成legend
figure.subplots_adjust(right=0.7)
j+=1
#绘制平行于x轴的虚线
for i in range(1, 11, 1):
plt.axhline(y=i/10, linestyle="dashed", color="black", linewidth=0.5)
labels = ax.get_xticklabels() + ax.get_yticklabels()
#设置数字label字体
[label.set_fontname("Times New Roman") for label in labels]
plt.savefig(r"filename.svg", format="svg")
plt.show()以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

