의 작성자는 범주 형 데이터 프레임 으로 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().
