使用sns.axes_style()后Matplotlib图表中文显示为方块的问题求助
Seaborn上下文管理器中中文显示方块的解决方法
问题重现
原本代码可正常显示中文标签:
import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示中文 revenue = ["133", "111", "1145"] depense = ["13", "56", "66"] date = ["7月10日", "7月11日", "7月12日"] fig, ax = plt.subplots() ax.plot(date, revenue, label="收益") ax.plot(date, depense, label="支出") ax.legend() plt.show()
但添加Seaborn样式设置和上下文管理器后,中文变为方块:
sns.set_style('whitegrid', {'font.sans-serif': ['SimHei']}) with sns.axes_style("whitegrid"): fig, ax = plt.subplots() ax.plot(date, revenue, label="收益") ax.plot(date, depense, label="支出") ax.legend() plt.show()
核心原因
Seaborn的axes_style上下文管理器会重置Matplotlib的rc参数,即使全局设置过字体,进入上下文后也会被覆盖为Seaborn默认样式的参数,导致中文字体失效。
解决方法
方法1:上下文管理器内重新设置字体
在with代码块内重新指定字体参数,确保上下文内的配置生效:
import seaborn as sns import matplotlib.pyplot as plt revenue = ["133", "111", "1145"] depense = ["13", "56", "66"] date = ["7月10日", "7月11日", "7月12日"] with sns.axes_style("whitegrid"): # 重新设置中文字体及负号显示 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False fig, ax = plt.subplots() ax.plot(date, revenue, label="收益") ax.plot(date, depense, label="支出") ax.legend() plt.show()
方法2:自定义样式传入上下文管理器
提前基于Seaborn的whitegrid样式扩展字体配置,再传入上下文管理器:
import seaborn as sns import matplotlib.pyplot as plt revenue = ["133", "111", "1145"] depense = ["13", "56", "66"] date = ["7月10日", "7月11日", "7月12日"] # 基于默认whitegrid样式添加字体配置 custom_style = sns.axes_style("whitegrid") custom_style.update({ 'font.sans-serif': ['SimHei'], 'axes.unicode_minus': False }) with sns.axes_style(custom_style): fig, ax = plt.subplots() ax.plot(date, revenue, label="收益") ax.plot(date, depense, label="支出") ax.legend() plt.show()
方法3:全局设置Seaborn样式并锁定字体
通过sns.set_style全局配置样式时,直接传入字体参数,后续上下文管理器会继承该配置:
import seaborn as sns import matplotlib.pyplot as plt # 全局设置whitegrid样式,同时指定中文字体 sns.set_style("whitegrid", { 'font.sans-serif': ['SimHei'], 'axes.unicode_minus': False }) revenue = ["133", "111", "1145"] depense = ["13", "56", "66"] date = ["7月10日", "7月11日", "7月12日"] with sns.axes_style("whitegrid"): fig, ax = plt.subplots() ax.plot(date, revenue, label="收益") ax.plot(date, depense, label="支出") ax.legend() plt.show()
补充:Windows下验证可用字体
如果不确定SimHei是否在Matplotlib的可用字体列表中,可运行以下代码查看:
from matplotlib.font_manager import FontManager mpl_fonts = set(f.name for f in FontManager().ttflist) print('Matplotlib可用字体列表:') for f in sorted(mpl_fonts): print('\t' + f)
内容的提问来源于stack exchange,提问作者ah bon
相关产品推荐
相关产品推荐

