问题描述
我有三个不同的数据框,看起来像这样:
>>> a b c d
aa 0.1 0.2 0.4 0.8
bb 0.3 0.5 0.9 0.5
cc 0.4 0.2 0.4 0.3
dd 0.8 0.1 0.3 0.4
3个数据帧之间的唯一区别是给定的数字。
我正在为每个数据帧创建for循环热图。我想根据df名称(例如df1,df2和df3)为每个热图赋予不同的标题。这就是我要这样做的方式(由于中间的计算不相关,所以我在中间剪掉了它们):
dfs=[df1,df2,df3]
for dfx in dfx:
#calculations.......
fix,ax=plt.subplots(figsize=(12,6))
cmap = plt.get_cmap('Greens_r',5)
cmap.set_over('lightgrey')# colour valued l
sns.set(rc={'figure.figsize':(10.7,10.27)})
#Create the heatmap,set title with string of df)
sns.heatmap(str(dfs),square=True,cmap=cmap,vmin=0.001,vmax=0.051,linewidths=.5,cbar_kws=
{"shrink": 0.8}).set_title(str(dfx),fontsize=20,pad=20)
plt.tick_params(axis='x',which='major',labelsize=14,labelbottom = False,bottom=False,top =
False,labeltop=True)
plt.xticks(rotation=70)
所以很明显 .set_title(str(dfx),fontsize = 20,pad = 20)只是给我整个数据框作为标题中的字符串而不是名称(第一个图表为df1, df2的第二个)。
我看到了这篇文章Get the name of a pandas DataFrame,但从那里看来,不可能将变量名作为字符串获取。
我的最终目标是能够根据数据框变量名称为三个图表(例如df1,df2,df3)的每一个赋予不同的标题
解决方法
因此python总体上与您的建议背道而驰。不幸的是,使用变量名作为字符串是非常棘手的。但是,您可以使用数据框字典(而不是数据框列表来获得相同的结果)。
dfs={"df1": df1,"df2": df2,"df3": df3}
for name,dfx in dfx.items():
#calculations.......
fix,ax=plt.subplots(figsize=(12,6))
cmap = plt.get_cmap('Greens_r',5)
cmap.set_over('lightgrey')# colour valued l
sns.set(rc={'figure.figsize':(10.7,10.27)})
#Create the heatmap,set title with string of df)
sns.heatmap(dfx,square=True,cmap=cmap,vmin=0.001,vmax=0.051,linewidths=.5,cbar_kws=
{"shrink": 0.8}).set_title(name,fontsize=20,pad=20)
plt.tick_params(axis='x',which='major',labelsize=14,labelbottom = False,bottom=False,top =
False,labeltop=True)
plt.xticks(rotation=70)