sns.heatmap()中文显示乱码

两种代码设置都是乱码

import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['simhei'] # 用来正常显示中文标签

sns.set()
# sns.set_style('whitegrid',{'font.sana-serif':['simhei','Arial']})
sns.set_style('whitegrid')

plt.figure(figsize=(10,6),dpi=600)
sns.heatmap(df_group_all[df_group_all.columns[0:10]],annot=True,cmap='coolwarm',fmt='d')
plt.show()

img

img

以下回答参考GPT并且由Bony-整理:
可能是因为当前环境下没有安装中文字体,你可以尝试以下两种解决方法:

  1. 安装中文字体

你可以在系统中安装中文字体,比如Windows系统中可以安装“宋体”、“黑体”等中文字体。安装完后,在代码中设置中文字体为安装的字体,例如:

plt.rcParams['font.sans-serif'] = ['SimSun']  # 设置字体为宋体
  1. 设置字体为系统自带的字体

如果无法安装中文字体,你可以将字体设置为系统自带的字体,例如:

plt.rcParams['font.sans-serif'] = ['Arial']  # 设置字体为Arial

或者:

plt.rcParams['font.sans-serif'] = ['Helvetica']  # 设置字体为Helvetica

这些字体通常都是可以正常显示中文的。

  • 这篇博客也许可以解决你的问题👉 :让 sns.heatmap 的数字不使用科学计数法
  • 除此之外, 这篇博客: 3种场景下的相关性计算方式,热力图优化展示中的 基础:sns.heatmap 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 一般常用sns.heatmap的热力图来展示变量之间的相关系数矩阵,下面是公众号:一直学习一直爽常用的两种配色样式,基本上可以解决90%的问题.在这里插入图片描述
    ,如果读者想进一步提升对热力图的使用技巧可查看Ultimate Guide to Heatmaps in Seaborn with Python

    data = pd.read_csv('https://raw.githubusercontent.com/drazenz/heatmap/master/autos.clean.csv')
    
    # 样式1
    fig, ax = plt.subplots(1, 1, figsize=(12, 12))
    sns.heatmap(data=data.corr(), 
                annot=True,
                annot_kws={"size":10},
                square=True,
                cmap="YlGnBu",
                fmt='.2f', 
                linewidths=0.5,
                linecolor='w',
                ax=ax)
    # 样式2
    fig, ax = plt.subplots(1, 1, figsize=(12, 12))
    sns.heatmap(data=data.corr(), 
                annot=True,
                annot_kws={"size":10},
                square=True,
                cmap=sns.diverging_palette(20, 220, n=256),
                fmt='.2f', 
                linewidths=0.5,
                linecolor='w',
                ax=ax)
    #ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
    
  • 以下回答由chatgpt基于相关博客总结生成:

    在sns.heatmap()中文显示乱码问题,可以按照以下步骤进行解决:

    1.导入字体库文件

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    
    # Windows系统字体库的路径
    my_font = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
    
    1. 在sns.heatmap()函数中加入字体参数
    sns.heatmap(data=data.corr(), 
                annot=True,
                annot_kws={"size":10},
                square=True,
                cmap=sns.diverging_palette(20, 220, n=256),
                fmt='.2f', 
                linewidths=0.5,
                linecolor='w',
                ax=ax,
                font=my_font)  # 加入字体参数
    
    1. 如果还不能解决问题,则可以使用以下代码更改matplotlib默认字体
    import matplotlib
    matplotlib.rcParams['font.family']='SimHei'  # 将字体设定为黑体
    

    如果以上方法都不能解决问题,则可以尝试以下步骤:

    1. 更新matplotlib和seaborn库至最新版本。

    如果以上步骤仍然不能解决问题,则该问题可能比较复杂,需要更深入的调查和分析,本人暂无其他解决方案。