我有三个不同的数据框,看起来与此类似:
>>> 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 为 df 的第 2) 个。
我看到了这篇文章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)
关于python - 将 dataframe-variable-name 作为 seaborn 图表的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63897588/