用python画热力图不难,但是想要调整热力图中的各种字体和颜色就需要深究其中各种参数的功能了,这里让我们看一下如何一步步实现如下图所示的热力图: 1、导入所需的各种包,特别关注其中关于字体的部分
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib as mpl
from matplotlib import cm
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib import rcParams
2、读入excel文件,路径因人而异
con_mat = pd.read_excel('文件路径', index_col=None, header=None)
3、df.dropna() 函数用于删除dataframe数据中的缺失数据
con_mat = con_mat.dropna(axis=1,how='all')
con_mat = con_mat.dropna(axis=0,how='any')
num_para = con_mat.iloc[:, 1].values-1
4、涉及到颜色的一些设置
viridis = cm.get_cmap('YlGnBu', 256)
newcolors = viridis(np.linspace(0, 1, 256))
pink = np.array([203/256, 4/256, 71/256, 1])
newcolors[208:, :] = pink
newcmp = ListedColormap(newcolors)
5、字体以及框架的一些设置
font_size = 40 * 16 * (1/len(num_para))
label_size = 27 * 16 * (1/len(num_para))
config = {
"font.family":'Times New Roman',
"font.size": font_size,
"axes.labelsize": 50,
"xtick.direction":'out',
"ytick.direction":'out',
"xtick.labelsize": label_size,
"ytick.labelsize": label_size,
}
rcParams.update(config)
range(1,con_mat.iloc[:,2:].shape[1])
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']
plt.rcParams['mathtext.fontset'] = 'stix'
con_mat.iloc[:,2:].iloc[1,1].round(2)
6、最后的作图部分
mask = np.zeros_like(con_mat.iloc[:,2:])
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
fig,ax=plt.subplots(1, 1, figsize=(30, 30))
ax = sns.heatmap(con_mat.iloc[:,2:], cmap=newcmp, cbar=False, vmin=-0.6, vmax=1, mask=mask, square=True)
for i in range(con_mat.iloc[:,2:].shape[0]):
for j in range(con_mat.iloc[:,2:].shape[1]):
if j<i:
text = ax.text(j+0.5,i+0.5,con_mat.iloc[:,2:].iloc[i,j].round(2),ha="center", va="center", color="k",fontsize=font_size , fontname='Times New Roman')
text = ax.text(1/2 * len(num_para)-0.38, 1/15 * len(num_para), 't ', ha="center", va="center", color="k", fontsize=100,
fontname='Times New Roman', fontweight='bold', style='italic')
text = ax.text(1/2 * len(num_para), 1/15 * len(num_para), ' = 3 s', ha="center", va="center", color="k", fontsize=100,
fontname='Times New Roman', fontweight='bold')
ax.spines['top'].set_visible(True)
ax.spines['right'].set_visible(True)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(True)
bwith = '10'
ax.spines['bottom'].set_linewidth(bwith)
ax.spines['left'].set_linewidth(bwith)
ax.spines['top'].set_linewidth(bwith)
ax.spines['right'].set_linewidth(bwith)
x = 10/11 * len(num_para)
y = 1/12 * len(num_para)
x_1 = -3/11 * len(num_para)
y_1 = 0 * len(num_para)
ax.tick_params(top='off',bottom='off',left='off',right='on')
ax.text(x, y, "(f)", fontsize=120, fontfamily='Arial', fontweight='bold')
x_label = []
x_label_total = ['A$_{MAX}$', 'Arial', 'Arial$^3$', 'CAA', 'CAA$^3$', 'CAA$_{input}$', 'CAD', 'CAD$_{input}$',
'CAV', 'CAV$^3$', 'CAV$_{input}$', 'ID', 'ID$_{input}$', 'Ia$_{input}$', 'Id2',
'Id2$^3$', 'Id2$_{input}$', 'Iv2', 'Iv2$^3$', 'Iv2$_{input}$', 'Pa', 'Pa$^3$', 'Pa$_{input}$',
'Pd', 'Pd$^3$', 'Pd$_{input}$', 'Pv', 'Pv$^3$', 'Pv$_{input}$', 'τc', 'ID$^3$', 'TP', 'Tva']
for i in num_para:
print(i)
x_label.append(x_label_total[i])
ax.set_xticklabels(x_label, rotation='vertical', fontfamily='Times New Roman')
ax.set_yticklabels(x_label, rotation='horizontal', fontfamily='Times New Roman')
ax.set_xlabel('')
ax.set_ylabel('')
|