【问题标题】:How to plot heatmap for high-dimensional dataset?如何绘制高维数据集的热图?
【发布时间】:2018-06-23 03:21:16
【问题描述】:

如果您能告诉我如何为具有大约 150 个特征的大型数据集绘制高分辨率热图,我将不胜感激。

我的代码如下:

XX = pd.read_csv('Financial Distress.csv')

y = np.array(XX['Financial Distress'].values.tolist())
y = np.array([0 if i > -0.50 else 1 for i in y])
XX = XX.iloc[:, 3:87]
df=XX
df["target_var"]=y.tolist()
target_var=["target_var"]

fig, ax = plt.subplots(figsize=(8, 6))
correlation = df.select_dtypes(include=['float64',
                                             'int64']).iloc[:, 1:].corr()
sns.heatmap(correlation, ax=ax, vmax=1, square=True)
plt.xticks(rotation=90)
plt.yticks(rotation=360)
plt.title('Correlation matrix')
plt.tight_layout()
plt.show()
k = df.shape[1]  # number of variables for heatmap
fig, ax = plt.subplots(figsize=(9, 9))
corrmat = df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corrmat, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
cols = corrmat.nlargest(k, target_var)[target_var].index
cm = np.corrcoef(df[cols].values.T)
sns.set(font_scale=1.0)
hm = sns.heatmap(cm, mask=mask, cbar=True, annot=True,
                 square=True, fmt='.2f', annot_kws={'size': 7},
                 yticklabels=cols.values,
                 xticklabels=cols.
                 values)
plt.xticks(rotation=90)
plt.yticks(rotation=360)
plt.title('Annotated heatmap matrix')
plt.tight_layout()
plt.show()

它工作正常,但为具有 40 多个特征的数据集绘制的热图太小。

提前致谢,

【问题讨论】:

  • @Mr.T 非常感谢您的时间和考虑。我试过 'figsize=(200, 200),dpi=150' 但我不知道为什么它没有改善很多。我的数据集的一部分在这里:kaggle.com/shebrahimi/financial-distress
  • @Mr.T 此外,如果有用的话,我不知道如何使用 plotly。 plot.ly
  • 您尝试保存图形,还是仅使用 plt.show()?当你保存为 pdf 时会发生什么?
  • 感谢您的时间和考虑。我已经尝试过 fig.savefig('heat.png') 和 fig.savefig('heat.pdf') 但它没有任何区别。 @MarkTeese

标签: python-3.x data-visualization heatmap seaborn


【解决方案1】:

调整 figsize 和 dpi 对我有用。

我调整了您的代码并将热图的大小翻倍至 165 x 165。渲染需要一段时间,但 png 看起来不错。我的后端是“module://ipykernel.pylab.backend_inline”。

正如我最初的回答中所述,我很确定您在创建新对象之前忘记关闭图形对象。如果您得到奇怪的效果,请在 fig, ax = plt.subplots() 之前尝试 plt.close("all")

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

print(plt.get_backend())

# close any existing plots
plt.close("all")

df = pd.read_csv("Financial Distress.csv")
# select out the desired columns
df = df.iloc[:, 3:].select_dtypes(include=['float64','int64'])

# copy columns to double size of dataframe
df2 = df.copy()
df2.columns = "c_" + df2.columns
df3 = pd.concat([df, df2], axis=1)

# get the correlation coefficient between the different columns
corr = df3.iloc[:, 1:].corr()
arr_corr = corr.as_matrix()
# mask out the top triangle
arr_corr[np.triu_indices_from(arr_corr)] = np.nan

fig, ax = plt.subplots(figsize=(24, 18))

hm = sns.heatmap(arr_corr, cbar=True, vmin=-0.5, vmax=0.5,
                 fmt='.2f', annot_kws={'size': 3}, annot=True, 
                 square=True, cmap=plt.cm.Blues)

ticks = np.arange(corr.shape[0]) + 0.5
ax.set_xticks(ticks)
ax.set_xticklabels(corr.columns, rotation=90, fontsize=8)
ax.set_yticks(ticks)
ax.set_yticklabels(corr.index, rotation=360, fontsize=8)

ax.set_title('correlation matrix')
plt.tight_layout()
plt.savefig("corr_matrix_incl_anno_double.png", dpi=300)

全图: 左上部分的缩放:

【讨论】:

  • 非常感谢您的时间和考虑。抱歉,但正如我提到的,这个数据集大约是我数据的一半。真的,我只是为它添加了一些新功能(我为它创建了大约 50 多个功能),所以热图仍然很小。 @MarkTeese 非常感谢。
  • 我已经更新了我的答案,以包含来自所提供数据的巨大 (165x165) 热图。我建议使用来自 kaggle 的可用 csv 来运行我的代码,并更多地使用 figsize 和文本大小。
  • 能否请您告诉我是否可以将这样的大图绘制为 12 张单独的图片(每张单独的图片将显示大图的某些部分)?像this 这样的东西。谢谢。
【解决方案2】:

如果我正确理解你的问题,我认为你所要做的就是增加你的身材:

f, ax = plt.subplots(figsize=(20, 20))

而不是

f, ax = plt.subplots(figsize=(9, 9))

【讨论】:

  • 非常感谢。我试图增加 figsize 和 dpi 但我无法解决问题。 @wordsforthewise
  • 那我猜这个问题还不清楚。 “热图太小”是什么意思?
  • 抱歉,我插入了绘制的热图以显示我所说的太小。谢谢。 @wordsforthewise
  • 此外,如果无法为大约 150 个特征绘制热图,请告诉我是否可以仅为最相关的特征绘制热图?这样做在社区中是否被广泛接受?他们在高维数据的情况下做什么?
  • 是的,您可以使用 df.corr() > 0.5 或类似的东西过滤相关性。我不确定任何“最佳实践”,但我可能只会查看您的案例中最相关的功能。这取决于你想做什么。
猜你喜欢
  • 2016-07-20
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 2021-02-27
  • 2019-10-17
  • 2015-06-07
  • 2019-11-06
  • 1970-01-01
相关资源
最近更新 更多