2017-04-19 192 views
3

我正在学习关于数据可视化的UDemy课程(我向你推荐它,但它可能看起来像垃圾邮件),在那之前,我一直在使用matplotlib来做我的可视化,所以Seaborn是相当的对我来说是新的。在过程中,他们谈论corrplot()功能,可生成类似如下图:Python,Seaborn:如何复制corrplot?

enter image description here

但现在,corrplot()已被弃用。我一直在寻找的Seaborn文档中,并在网络上一些链接,而“更紧密”我所做的是这样的:

enter image description here

当然,我喜欢更原始corrplot()输出,它的方法更容易实现,使用heatmap()或其他函数做同样的事情的方式是什么?

顺便说一句:生成图表的数据是不同的,第一个来自视频的捕获,而另一个是我的PC的屏幕截图,所以值不一样。

回答

3

首先,corrplot()折旧的事实并不意味着您不能使用它。它很可能会在未来版本的seaborn中被删除,或者有其他一些问题随之出现。但是,如果您对现在给您的产品感到满意,您仍然可以使用它。

为了得到类似于corrplot的结果,但使用了heatmap,您可能需要稍微调整一下。

一个示例如下所示:

import numpy as np; np.random.seed(1) 
import pandas as pd 
import seaborn.apionly as sns 
import matplotlib.pyplot as plt 

# Generate a random dataset 
cols = [s*4 for s in list("ABCD")] 
df = pd.DataFrame(data=np.random.rayleigh(scale=5, size=(100, 4)), columns=cols) 

# Compute the correlation matrix 
corr = df.corr() 
print(corr) 
# Generate a mask for the upper triangle 
mask = np.zeros_like(corr, dtype=np.bool) 
mask[np.triu_indices_from(mask)] = True 

# Set up the matplotlib figure 
fig, ax = plt.subplots() 

# Draw the heatmap with the mask and correct aspect ratio 
vmax = np.abs(corr.values[~mask]).max() 
sns.heatmap(corr, mask=mask, cmap=plt.cm.PuOr, vmin=-vmax, vmax=vmax, 
      square=True, linecolor="lightgray", linewidths=1, ax=ax) 
for i in range(len(corr)): 
    ax.text(i+0.5,len(corr)-(i+0.5), corr.columns[i], 
      ha="center", va="center", rotation=45) 
    for j in range(i+1, len(corr)): 
     s = "{:.3f}".format(corr.values[i,j]) 
     ax.text(j+0.5,len(corr)-(i+0.5),s, 
      ha="center", va="center") 
ax.axis("off") 
plt.show() 

enter image description here