利用水平条形图探索实验室感染数量
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines
from matplotlib import patches
from matplotlib.patheffects import withStroke
数据探索
以下数据如果有需要的同学可关注公众号HsuHeinrich,回复【数据可视化】自动获取~
# 自定义数据(来源于原始图标推断的数据,并非原始数据计算或者随机自定义)
counts = [6, 7, 7, 9, 11, 15, 17, 18, 54]
names = [
"Hantavirus", "Tularemia", "Dengue", "Ebola", "E. coli",
"Tuberculosis", "Salmonella", "Vaccinia", "Brucella"
]
# 条形图位置
y = [i * 0.9 for i in range(len(names))]
绘制基本条形图
# 定义颜色
BLUE = "#076fa2"
RED = "#E3120B"
BLACK = "#202020"
GREY = "#a2a2a2"
fig, ax = plt.subplots(figsize=(12, 7))
ax.barh(y, counts, height=0.55, align="edge", color=BLUE);
自定义布局
# 自定义x轴刻度
ax.xaxis.set_ticks([i * 5 for i in range(0, 12)]) # x刻度位置
ax.xaxis.set_ticklabels([i * 5 for i in range(0, 12)], size=16, fontfamily="Econ Sans Cnd", fontweight=100) # x刻度标签
ax.xaxis.set_tick_params(labelbottom=False, labeltop=True, length=0) # x刻度参数
# 指着轴范围
ax.set_xlim((0, 55.5))
ax.set_ylim((0, len(names) * 0.9 - 0.2))
# 设置网格线
ax.set_axisbelow(True) # 网格线绘制在图像和刻度标签之下
ax.grid(axis = "x", color="#A8BAC4", lw=1.2) # 指定x轴网格线的颜色和线宽
ax.spines["right"].set_visible(False) # 去掉右边框
ax.spines["top"].set_visible(False) # 去掉顶边框
ax.spines["bottom"].set_visible(False) # 去掉底边框
ax.spines["left"].set_lw(1.5) # 保留左边框,并设置线宽
ax.spines["left"].set_capstyle("butt") # 左脊线的线帽样式
# 隐藏y轴
ax.yaxis.set_visible(False)
fig
添加标签
PAD = 0.3
for name, count, y_pos in zip(names, counts, y):
x = 0
color = "white"
path_effects = None
if count < 8:
x = count
color = BLUE
path_effects=[withStroke(linewidth=6, foreground="white")]
ax.text(
x + PAD, y_pos + 0.5 / 2, name,
color=color, fontfamily="Econ Sans Cnd", fontsize=18, va="center",
path_effects=path_effects
)
fig
添加必要注释信息
# 调整布局
fig.subplots_adjust(left=0.005, right=1, top=0.8, bottom=0.1)
# 标题
fig.text(
0, 0.925, "Escape artists",
fontsize=22, fontweight="bold", fontfamily="Econ Sans Cnd"
)
# 副标题
fig.text(
0, 0.875, "Number of laboratory-acquired infections, 1970-2021",
fontsize=20, fontfamily="Econ Sans Cnd"
)
# 说明
source = "Sources: Laboratory-Acquired Infection Database; American Biological Safety Association"
fig.text(
0, 0.06, source, color=GREY,
fontsize=14, fontfamily="Econ Sans Cnd"
)
# 著作信息
fig.text(
0, 0.005, "The Economist", color=GREY,
fontsize=16, fontfamily="Lato"
)
# 添加顶部水平线
fig.add_artist(lines.Line2D([0, 1], [1, 1], lw=3, color=RED, solid_capstyle="butt"))
fig.add_artist(patches.Rectangle((0, 0.975), 0.05, 0.025, color=RED))
# 设置背景色
fig.set_facecolor("white")
fig
参考:Horizontal barplot with Matplotlib
共勉~