两种代码设置都是乱码
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()
以下回答参考GPT并且由Bony-整理:
可能是因为当前环境下没有安装中文字体,你可以尝试以下两种解决方法:
你可以在系统中安装中文字体,比如Windows系统中可以安装“宋体”、“黑体”等中文字体。安装完后,在代码中设置中文字体为安装的字体,例如:
plt.rcParams['font.sans-serif'] = ['SimSun'] # 设置字体为宋体
如果无法安装中文字体,你可以将字体设置为系统自带的字体,例如:
plt.rcParams['font.sans-serif'] = ['Arial'] # 设置字体为Arial
或者:
plt.rcParams['font.sans-serif'] = ['Helvetica'] # 设置字体为Helvetica
这些字体通常都是可以正常显示中文的。
一般常用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)
在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)
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) # 加入字体参数
import matplotlib
matplotlib.rcParams['font.family']='SimHei' # 将字体设定为黑体
如果以上方法都不能解决问题,则可以尝试以下步骤:
如果以上步骤仍然不能解决问题,则该问题可能比较复杂,需要更深入的调查和分析,本人暂无其他解决方案。