2017-04-19 137 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