用matplotlib绘制带误差的条形图及中英文字体设置

时间:2021-02-13 03:01:02
 #!/usr/bin/env python3

 ## 以下是一个带误差条的条形图的例子,演示了误差条形图的绘制及中英文字体设置
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties as FP # %matplotlib inline
# %config InlineBackend.figure_format = 'svg' mpl.rcParams['text.usetex'] = False
mpl.rcParams['figure.figsize'] = (7.40, 5.55) # unit: inch
mpl.rcParams['figure.frameon'] = False ## 中文设置
# matplotlib默认不支持ttc,所以可以将ttc转换ttf先。
# 将Windows字体 simsun.ttc上传到 https://transfonter.org/ttc-unpack 在线转换成TTF,
# 得到simsun.ttf和nsimsun.ttf,将两个ttf文件放到PYTHON安装目录的
# Lib\site-packages\matplotlib\mpl-data\fonts\ttf 子目录下。
# 删除字体缓存以便重新生成字体缓存:$HOME/.matplotlib/fontList.py3k.cache # 全局中文设置
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'NSimSun,Times New Roman' # 局部中文:设置分别为中文和英文设置两个FontProperties,以便局部切换中英文字体
cfp = FP('NSimSun', size=12)
efp = FP('Times New Roman', size=12) fig,ax = plt.subplots() xticklabels = ('G1', 'G2', 'G3')
ylabel = 'd' male_means = (9, 10, 9)
male_std = (4.66, 3.52, 5.32)
female_means = (12, 14, 12)
female_std = (6.96, 5.46, 3.61)
title = 'XX实验结果' N=3
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
with plt.style.context(('ggplot')):
rects1 = ax.bar(
ind - 0.02, female_means, width, color='darkgrey', yerr=female_std)
rects2 = ax.bar(
ind + 0.02 + width,
male_means,
width,
color='lightgrey',
yerr=male_std) ax.set_ylabel('d', fontproperties=efp, rotation=0)
# 在label、title中可用参数'fontproperties' 指定字体 ax.yaxis.set_label_coords(-0.05, 0.95)
ax.set_title(title)
ax.set_xticks(ind + width / 2) ax.set_xticklabels(xticklabels, fontproperties=efp) ax.legend((rects1[0], rects2[0]), ('处理A', '处理B'), prop=cfp, framealpha=0)
# 在legend中可用参数'prop'指定字体,注意不是'fontproperties' def autolabel(rects, yerr):
"""
Attach a text label above each bar displaying its height
"""
for i in range(0, N):
rect = rects[i]
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2.,
1.05 * height,
'%0.2f' % yerr[i],
ha='left',
va='bottom',
family='Georgia',
fontsize=9)
#在text函数中可用family和fontsize指定字体 autolabel(rects1, female_means)
autolabel(rects2, male_means) ax.text(
1,
20,
'Hello World',
color = 'b',
ha='left',
va='bottom',
fontproperties=efp)
# 在text函数中也可用fontproperties指定字体 fig.tight_layout()
fig.savefig('filename.svg', format='svg')
# 保存为矢量图svg格式,如需插入word,可以用inkscape软件将其转换成emf格式