当使用 Seaborn 设置风格时,Seaborn 可能会重置一些 matplotlib 的全局参数,包括字体设置。因此,如果你在 Seaborn 风格设置之前设置中文字体,Seaborn 的风格设置可能会覆盖你的字体设置,导致中文无法正常显示。
正确的顺序应该是:
1. 先设置 Seaborn 的风格。
2. 然后再设置中文字体。
这样可以确保 Seaborn 的风格应用后,中文字体仍然能够被正确加载。
示例代码:
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import font_manager
# 设置Seaborn风格和调色板
sns.set(style="whitegrid", palette="muted")
# 手动添加中文字体路径(SimHei)
font_path = 'C:/Windows/Fonts/simhei.ttf' # 替换为你系统中的实际路径
font_manager.fontManager.addfont(font_path)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置为黑体字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 你的绘图代码
plt.figure(figsize=(10, 6))
sample_data = magnetic_flux_density.sample(n=5, axis=0)
sns.boxplot(data=sample_data.T)
# 设置标题,使用中文字体
plt.title("随机抽取的5行数据的箱型图", fontsize=16)
plt.show()
总结:
Seaborn 风格设置可能会重置一些字体相关的配置,因此先设置 Seaborn 风格,再设置中文字体,是保证中文正常显示的最佳做法。