【问题标题】:How to combine two heatmaps in Seaborn in Python so both are shown in the same heatmap?如何在 Python 中组合 Seaborn 中的两个热图,以便两者都显示在同一个热图中?
【发布时间】:2021-02-10 05:31:31
【问题描述】:

这是我正在使用的数据的链接: 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'))

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

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

同时并排显示数据。有没有简单的方法来实现?

【问题讨论】:

  • @JohanC 是类似的东西,但我使用的是从 CSV 导入的 Dataframe。他们正在使用数组。我想知道 seaborn 或 pyplot 是否有这种方法
  • @Coder88 df.valuesdf.to_numpy() 将为您提供底层 numpy 数组。
  • @QuangHoang 是的,它现在可以工作了。但是第二个情节的颜色几乎都一样。那么标签和色阶呢?

标签: python matplotlib seaborn data-visualization heatmap


【解决方案1】:

带有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')
                            )

输出:

【讨论】:

  • 太棒了,我不明白为什么红色刻度在您的输出中显示为 0 到 350%。在我的输出中,它正确显示 0 - ca 80%。不过我的问题已经解决了,谢谢你的时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 2018-11-29
  • 2021-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多