gpt4 book ai didi

python - 如何在 Python 中结合 Seaborn 中的两个热图,以便两者都显示在同一个热图中?

转载 作者:行者123 更新时间:2023-12-04 08:41:12 24 4
gpt4 key购买 nike

这是指向我正在使用的数据的链接: https://github.com/fivethirtyeight/data/tree/master/drug-use-by-age

我正在使用 Jupyter Lab,这是代码:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sb

url = 'https://raw.githubusercontent.com/fivethirtyeight/data/master/drug-use-by-age/drug-use-by-age.csv'

df = pd.read_csv(url, index_col = 0)

df.dtypes
df.replace('-', np.nan, inplace=True)
df = df.iloc[:,:].astype(float)
df = df.loc[:, df.columns != 'n']
#df.columns = df.columns.str.rstrip('-use')
df

fig, axes = plt.subplots(1,2, figsize=(20, 8))

fig.subplots_adjust(wspace=0.1)
fig.colorbar(ax.collections[0], ax=ax,location="right", use_gridspec=False, pad=0.2)
#plt.figure(figsize=(16, 16))
df_percentage = df.iloc[:,range(0,26,2)]
plot_precentage = sb.heatmap(df_percentage, cmap='Reds', ax=axes[0], cbar_kws={'format': '%.0f%%', 'label': '% used in past 12 months'})
df_frequency = df.iloc[:,range(1,27,2)]
plot_frequency = sb.heatmap(df_frequency, cmap='Blues', ax=axes[1], cbar_kws= dict(label = 'median frequency a user used'))

我可以在单独图表的子图中显示其中两个。

我想让它看起来像这样(这是用油漆做的):

enter image description here

同时并排显示数据。有没有一种简单的方法可以实现这一点?

最佳答案

带有mask 选项的非常简单的解决方案:

mask = np.vstack([np.arange(df.shape[1])]* df.shape[0]) % 2

fig, axes = plt.subplots()

plot_precentage = sns.heatmap(df,mask=mask, cmap='Reds', ax=axes,
cbar_kws={'format': '%.0f%%',
'label': '% used in past 12 months'}
)

plot_frequency = sns.heatmap(df, mask=1-mask, cmap='Blues', ax=axes,
cbar_kws= dict(label = 'median frequency a user used')
)

输出:

enter image description here

关于python - 如何在 Python 中结合 Seaborn 中的两个热图,以便两者都显示在同一个热图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64562879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com