[python] Pandas DataFrame에서 히트 맵 만들기

Python의 Pandas 패키지에서 생성 된 데이터 프레임이 있습니다. Pandas 패키지에서 DataFrame을 사용하여 히트 맵을 생성하려면 어떻게해야합니까?

import numpy as np 
from pandas import *

Index= ['aaa','bbb','ccc','ddd','eee']
Cols = ['A', 'B', 'C','D']
df = DataFrame(abs(np.random.randn(5, 4)), index= Index, columns=Cols)

>>> df
          A         B         C         D
aaa  2.431645  1.248688  0.267648  0.613826
bbb  0.809296  1.671020  1.564420  0.347662
ccc  1.501939  1.126518  0.702019  1.596048
ddd  0.137160  0.147368  1.504663  0.202822
eee  0.134540  3.708104  0.309097  1.641090
>>> 



답변

원하는 matplotlib.pcolor:

import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

이것은 다음을 제공합니다.

출력 샘플


답변

오늘 이것을보고있는 사람들에게는 여기에heatmap() 설명 된 Seaborn 을 추천합니다 .

위의 예는 다음과 같이 수행됩니다.

import numpy as np
from pandas import DataFrame
import seaborn as sns
%matplotlib inline

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

sns.heatmap(df, annot=True)

%matplotlib익숙하지 않은 사람들을위한 IPython 매직 기능은 어디에 있습니까 ?


답변

말마다 플롯이 필요하지 않고 테이블 형식으로 값을 표현하기 위해 색상을 추가하는 데 관심이 있다면 style.background_gradient()pandas 데이터 프레임 의 방법을 사용할 수 있습니다 . 이 방법은 예를 들어 JupyterLab 노트북에서 팬더 데이터 프레임을 볼 때 표시되는 HTML 테이블을 색상 화하며 결과는 스프레드 시트 소프트웨어에서 “조건부 서식”을 사용하는 것과 유사합니다.

import numpy as np
import pandas as pd


index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')

여기에 이미지 설명 입력

자세한 사용법은 이전에 동일한 주제에 대해 제공 한보다 정교한 답변pandas 문서스타일링 섹션을 참조하십시오 .


답변

유용한 sns.heatmapAPI가 여기 있습니다 . 매개 변수를 확인하십시오. 많은 수가 있습니다. 예:

import seaborn as sns
%matplotlib inline

idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)

# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

여기에 이미지 설명 입력


답변

당신이 팬더 DataFrame에서 대화 형 히트 맵을 원하고 당신이 Jupyter 노트북을 실행하는 경우 대화 형 위젯 시도 할 수 있습니다 Clustergrammer – 위젯 , NBViewer에 대화 형 노트북을 참조 여기에 , 문서를 여기에

여기에 이미지 설명 입력

더 큰 데이터 세트의 경우 개발중인 Clustergrammer2 WebGL 위젯 ( 여기에서 예제 노트북 )을 사용해 볼 수 있습니다.


답변

의 작성자는 범주 형 데이터 프레임 으로 seaborn만 작업 하기 seaborn.heatmap원합니다 . 일반적이지 않습니다.

색인과 열이 숫자 및 / 또는 날짜 / 시간 값인 경우이 코드가 잘 작동합니다.

Matplotlib 히트 매핑 함수 pcolormesh에는 indices 대신 bin이 필요 하므로 데이터 프레임 인덱스에서 bin을 빌드하는 멋진 코드가 있습니다 (인덱스의 간격이 균등하지 않더라도!).

나머지는 간단 np.meshgrid하고 plt.pcolormesh.

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

def conv_index_to_bins(index):
    """Calculate bins to contain the index values.
    The start and end bin boundaries are linearly extrapolated from
    the two first and last values. The middle bin boundaries are
    midpoints.

    Example 1: [0, 1] -> [-0.5, 0.5, 1.5]
    Example 2: [0, 1, 4] -> [-0.5, 0.5, 2.5, 5.5]
    Example 3: [4, 1, 0] -> [5.5, 2.5, 0.5, -0.5]"""
    assert index.is_monotonic_increasing or index.is_monotonic_decreasing

    # the beginning and end values are guessed from first and last two
    start = index[0] - (index[1]-index[0])/2
    end = index[-1] + (index[-1]-index[-2])/2

    # the middle values are the midpoints
    middle = pd.DataFrame({'m1': index[:-1], 'p1': index[1:]})
    middle = middle['m1'] + (middle['p1']-middle['m1'])/2

    if isinstance(index, pd.DatetimeIndex):
        idx = pd.DatetimeIndex(middle).union([start,end])
    elif isinstance(index, (pd.Float64Index,pd.RangeIndex,pd.Int64Index)):
        idx = pd.Float64Index(middle).union([start,end])
    else:
        print('Warning: guessing what to do with index type %s' %
              type(index))
        idx = pd.Float64Index(middle).union([start,end])

    return idx.sort_values(ascending=index.is_monotonic_increasing)

def calc_df_mesh(df):
    """Calculate the two-dimensional bins to hold the index and
    column values."""
    return np.meshgrid(conv_index_to_bins(df.index),
                       conv_index_to_bins(df.columns))

def heatmap(df):
    """Plot a heatmap of the dataframe values using the index and
    columns"""
    X,Y = calc_df_mesh(df)
    c = plt.pcolormesh(X, Y, df.values.T)
    plt.colorbar(c)

을 사용하여 호출하고을 사용하여 heatmap(df)확인하십시오 plt.show().

여기에 이미지 설명 입력


답변