seaborn绘图时,文字以及上下标乱码问题

问题描述

使用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'],和上面提到的代码在本例中是等效的


在这里插入图片描述

解决问题的办法不止一种,如果上下角标乱码,或者想添加上下标,也可以使用如下方法

参考:python 绘图 实现图中为字体添加下标、上标

1. 目录 1. 目录 2 2. 绘图函数Plotting functions 4 2.1. 可视化的统计关系Visualizing statistical relationships 4 2.1.1. 用散点图联系变量Relating variables with scatter plots 4 2.1.2. 强调线条图的连续性Emphasizing continuity with line plots 10 2.1.3. 显示与切面的多个关系Showing multiple relationships with facets 21 2.2. 分类数据绘图Plotting with categorical data 24 2.2.1. 分类散点图Categorical scatterplots 26 2.2.2. 分类观测值分布Distributions of observations within categories 31 2.2.3. 分类统计估计Statistical estimation within categories 37 2.2.4. 对“wide-form”数据作图Plotting “wide-form” data 41 2.2.5. 显示与facet的多个关系Showing multiple relationships with facets 43 2.3. 可视化数据集的分布Visualizing the distribution of a dataset 44 2.3.1. 绘制单变量分布Plotting univariate distributions 45 2.3.2. 绘制二元分布Plotting bivariate distributions 51 2.3.3. 在数据集中可视化成对关系Visualizing pairwise relationships in a dataset 55 2.4. 可视化线性关系Visualizing linear relationships 57 2.4.1. 函数绘制线性模型Functions to draw linear regression models 58 2.4.2. 拟合不同种类的模型Fitting different kinds of models 61 2.4.3. 在其他变量上的情况Conditioning on other variables 68 2.4.4. 控制图表的大小和形状Controlling the size and shape of the plot 71 2.4.5. 在其他上下文中绘制回归图Plotting a regression in other contexts 73 3. 多图网格Multi-plot grids 76 3.1. 构建结构化的多图网格Building structured multi-plot grids 76 3.2. 有条件的小倍数Conditional small multiples 77 3.3. 使用定制函数Using custom functions 86 3.4. 绘制成对的数据关系Plotting pairwise data relationships 90 4. 绘图美学Plot aesthetics 99 4.1. 控制图表美学Controlling figure aesthetics 99 4.1.1. Seaborn图表风格Seaborn figure styles 101 4.1.2. 删除轴上的小凸起Removing axes spines 104 4.1.3. 临设置图表样式Temporarily setting figure style 105 4.1.4. 覆盖Seaborn样式的元素Overriding elements of the seaborn styles 106 4.1.5. 缩放图表元素Scaling plot elements 108 4.2. 选择调色板Choosing color palettes 111 4.2.1. 创建颜色调色板Building color palettes 111 4.2.2. 定性调色板Qualitative color palettes 112 4.2.3. 连续调色板Sequential color palettes 116 4.2.4. 不同颜色的调色板Diverging color palettes 122 4.2.5. 设置默认调色板Setting the default color palette 124 5. 教程中的数据集 125
回答: 在使用python seaborn进行画图,可能会遇到中文乱码问题。这是由于seaborn是基于matplotlib实现的,而在运行seaborn的一些设置会覆盖掉matplotlib中的设置,导致中文乱码。解决这个问题的方式有几种途径。一种方式是在使用matplotlib进行画图,通过设置字体为中文宋体来解决乱码问题。体的代码如下: ```python import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['STSong'] plt.rcParams['axes.unicode_minus'] = False ``` 另外一种方式是在使用seaborn进行画图,同样设置字体为中文宋体。具体的代码如下: ```python import seaborn as sns sns.set(font='SimHei') ``` 通过以上的设置,即可解决python seaborn画图中文乱码问题。希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [解决python中matplotlib与seaborn画图中文乱码的根本问题:](https://blog.csdn.net/qq_45345462/article/details/118685228)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [python中Matplotlib、seaborn中英文乱码终极解决方案](https://blog.csdn.net/SunStrongInChina/article/details/123274028)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [【Python】一步解决绘图中文乱码问题(不需要额外下载字体)](https://blog.csdn.net/qq_43215869/article/details/121865164)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值