2016-09-09 9 views
7

히트 맵을 사용하여 상관 관계 행렬을 나타내려고합니다. R에 correlogram이라는 이름이 있지만, 파이썬에는 그런 것이 없다고 생각합니다.상관 관계 히트 맵

어떻게하면됩니까? 값은 예를 들어, -1에서 1로 이동 :

[[ 1.   0.00279981 0.95173379 0.02486161 -0.00324926 -0.00432099] 
[ 0.00279981 1.   0.17728303 0.64425774 0.30735071 0.37379443] 
[ 0.95173379 0.17728303 1.   0.27072266 0.02549031 0.03324756] 
[ 0.02486161 0.64425774 0.27072266 1.   0.18336236 0.18913512] 
[-0.00324926 0.30735071 0.02549031 0.18336236 1.   0.77678274] 
[-0.00432099 0.37379443 0.03324756 0.18913512 0.77678274 1.  ]] 

내가 다른 question에 따라 다음 히트 맵을 생성 할 수 있었다, 그러나 문제는 내 값은 0에서 '잘라 내기'를 얻을 것입니다, 그래서 내가 좋아하는 것 파란색 (-1)에서 빨간색 (1) 또는 그와 비슷한 값을 갖는지도를 가지지 만 여기서 0 이하의 값은 적절한 방식으로 표시되지 않습니다.

enter image description here

는 여기에 대한 코드입니다 :

plt.imshow(correlation_matrix,cmap='hot',interpolation='nearest') 
+0

나는 질문을 편집했습니다. – Marko

답변

11

또 다른 대안은 공분산을 음모 시본의 히트 맵 기능을 사용하는 것입니다. 이 예제에서는 R의 ISLR 패키지에서 자동 데이터 세트를 사용합니다 (표시된 예제와 동일). 늦게 파티에

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True) 

def magnify(): 
    return [dict(selector="th", 
       props=[("font-size", "7pt")]), 
      dict(selector="td", 
       props=[('padding', "0em 0em")]), 
      dict(selector="th:hover", 
       props=[("font-size", "12pt")]), 
      dict(selector="tr:hover td:hover", 
       props=[('max-width', '200px'), 
         ('font-size', '12pt')]) 
] 

corr.style.background_gradient(cmap, axis=1)\ 
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\ 
    .set_caption("Hover to magify")\ 
    .set_precision(2)\ 
    .set_table_styles(magnify()) 

enter image description here

0
  1. 파란색과 빨간색 사이의 전환에는 '제트'색상 표를 사용하십시오.
  2. vmin, vmax 매개 변수가있는 pcolor()을 사용하십시오.

이 대답에 자세히 설명되어 있습니다 : https://stackoverflow.com/a/3376734/21974

+0

내 경우에 예제를 들려 주시겠습니까? 파이썬에 익숙하지 않아서 문제가 있습니다. 당신이 준 예제에서 그들은 X, Y = np.meshgrid (x, y)를 사용합니다. – Marko

+0

meshgrid는 히트 맵으로 플롯되도록 각 점에 좌표 쌍을 지정하기위한 것입니다. – ypnos

0

을,하지만 난 느낌 : 당신이 더 화려한되고 싶었 경우

import pandas.rpy.common as com 
import seaborn as sns 
%matplotlib inline 

# load the R package ISLR 
infert = com.importr("ISLR") 

# load the Auto dataset 
auto_df = com.load_data('Auto') 

# calculate the correlation matrix 
corr = auto_df.corr() 

# plot the heatmap 
sns.heatmap(corr, 
     xticklabels=corr.columns, 
     yticklabels=corr.columns) 

enter image description here

, 당신은 예를 들어, Pandas Style을 사용할 수 있습니다 걸출한 해저 corrplot은 더 이상 사용되지 않을 것이라는 발표가 있은 후에 제가 함께 모아 놓은 것입니다. 다음 스 니펫은 seaborn heatmap을 기반으로 유사한 상관 관계 도표를 만듭니다. 색상 범위를 지정하고 중복 상관 관계를 삭제할지 여부를 선택할 수도 있습니다. 나는 당신과 같은 번호를 사용했음을 주목하되, 판다 데이터 프레임에 넣었습니다. 색상의 선택에 관해서는 sns.diverging_palette에 대한 문서를 볼 수 있습니다.

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

# A list with your data slightly edited 
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099, 
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443, 
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756, 
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512, 
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274, 
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00] 

# Split list 
n = 6 
data = [l[i:i + n] for i in range(0, len(l), n)] 

# A dataframe 
df = pd.DataFrame(data) 

def CorrMtx(df, dropDuplicates = True): 

    # Your dataset is already a correlation matrix. 
    # If you have a dateset where you need to include the calculation 
    # of a correlation matrix, just uncomment the line below: 
    # df = df.corr() 

    # Exclude duplicate correlations by masking uper right values 
    if dropDuplicates:  
     mask = np.zeros_like(df, dtype=np.bool) 
     mask[np.triu_indices_from(mask)] = True 

    # Set background color/chart style 
    sns.set_style(style = 'white') 

    # Set up matplotlib figure 
    f, ax = plt.subplots(figsize=(11, 9)) 

    # Add diverging colormap from red to blue 
    cmap = sns.diverging_palette(250, 10, as_cmap=True) 

    # Draw correlation plot with or without duplicates 
    if dropDuplicates: 
     sns.heatmap(df, mask=mask, cmap=cmap, 
       square=True, 
       linewidth=.5, cbar_kws={"shrink": .5}, ax=ax) 
    else: 
     sns.heatmap(df, cmap=cmap, 
       square=True, 
       linewidth=.5, cbar_kws={"shrink": .5}, ax=ax) 


CorrMtx(df, dropDuplicates = False) 

여기에 결과 플롯이다 : 당신은 파란색을 요청

enter image description here

,하지만 샘플 데이터의 범위를 벗어 떨어진다. 0.95173379를 -0으로 변경하십시오.모두 관측 95173379 당신은이를 얻을 것이다 : 당신이 확인할 수 있도록

enter image description here