利用以下代码,绘制皮尔逊相关系数热力图:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
city_ls = ['Beijing', 'Chengdu', 'Guangzhou', 'Shanghai', 'Shenyang']
def fileName(s):
return '{}PM20100101_20151231.csv'.format(s)
for city in city_ls:
file = fileName(city)
df = pd.read_csv(file)
col = df.columns
factor_ls = []
dis_ls = []
if city == 'Beijing':
factor_ls = [col[i] for i in range(len(col)) if i > 9 and pd.api.types.is_numeric_dtype(df[col[i]])]
else:
factor_ls = [col[i] for i in range(len(col)) if i > 8 and pd.api.types.is_numeric_dtype(df[col[i]])]
dis_ls = [c for c in col if c.startswith('PM_') and c != 'PM_US Post' and pd.api.types.is_numeric_dtype(df[c])]
df_china = df[dis_ls + factor_ls]
df_china = df_china.dropna()
if 'PM_US Post' in col and pd.api.types.is_numeric_dtype(df['PM_US Post']):
df_US = df[['PM_US Post'] + factor_ls]
df_US = df_US.dropna()
corr = df_china.corr(method='pearson')
# 设置图形大小
plt.figure(figsize=(12, 10))
sns.heatmap(corr, annot=True, cmap='coolwarm')
# 设置中文的字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus'] = False # 正常显示负号
plt.title(f'{city} Correlation Heatmap')
fig_file = f'./fig/{city}各区相关系数热力图.jpg'
plt.savefig(fig_file)
plt.show()
print(corr)
在Jupyter中,图片可以正常显示:
但是下载的png格式的图片却是空白:
如何让下载的图片可以正常显示?