问题描述
使用python seaborn绘制图表时,如果使用默认设置,那么会发现诸如汉字,上下角标的文字会出现乱码:
例如:下面用seaborn画一个柱状图
用到的数据格式如下:
问题复现
问题代码:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid")
# 画布设置
f, ax = plt.subplots(figsize=(6, 10))
# 绘图
sns.set_color_codes("pastel") #设置色调
sns.barplot(x="缺失比例", y="类别", data=data,
label="缺失比例", color="b")
ax.legend(ncol=1, loc="lower right", frameon=True) # 添加图例
ax.set(xlim=(0, 2), ylabel="")
plt.xlabel("数 据 缺 失 比 例(%)", fontsize=14) # 调整横轴标题字体
sns.despine(left=True, bottom=True) # 移除坐标轴的线
运行效果:
可以看到不只是中文,单位的上标,都不能正常显示
解决方法
通过
sns.set_style(style=None, rc=None)
,设置字体,这里推荐使用Microsoft Yahei,本例中使用如下代码
sns.set_style(rc= {'font.sans-serif':"Microsoft Yahei"})
,添加到原代码中。
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid")
sns.set_style(rc={'font.sans-serif':"Microsoft Yahei"})
# 画布设置
f, ax = plt.subplots(figsize=(6, 10))
# 绘图
sns.set_color_codes("pastel") #设置色调
sns.barplot(x="缺失比例", y="类别", data=data,
label="缺失比例", color="b")
ax.legend(ncol=1, loc="lower right", frameon=True) # 添加图例
ax.set(xlim=(0, 2), ylabel="")
plt.xlabel("数 据 缺 失 比 例(%)", fontsize=14) # 调整横轴标题字体
sns.despine(left=True, bottom=True) # 移除坐标轴的线
或者使用
plt.rcParams['font.sans-serif'] = ['Microsoft Yahei']
,和上面提到的代码在本例中是等效的
解决问题的办法不止一种,如果上下角标乱码,或者想添加上下标,也可以使用如下方法