在matplotlib子图中共享轴并删除未使用的

时间:2017-04-12 07:45:35

标签: python pandas matplotlib seaborn

我想在网格中绘制一系列seaborn热图。我知道子图的数量(可以是奇数或偶数)。 热图将显示平均占有率"星期几"星期几" (y轴)和"一天中的小时" (x轴),例如它们都共享相同的x / y域。

这是我目前的代码:

plt.savefig(figname,fotmat=figtype)

看起来几乎就像我想要的那样(最后几行): note axis labels, legend and "empty" subplots 但是想要我想要:

  • 每行只有一次y轴标签(DoW)(最左边的图)
  • 只在每行最右边的地块上设置色图图例(或者完全不让它,颜色是非常自我解释的)
  • 删除"空图"在最后一行,因为奇数总数

非常感谢任何提示

2 个答案:

答案 0 :(得分:2)

您可以更灵活,只需为每个存在的名称创建一个轴,如下所示:

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

days = ['Mon','Tue','Wed','Thurs','Fri','Sat','Sun']
names = [string.lowercase[i] for i in range(22)]

nItems = 1000

df = pd.DataFrame()
df['name'] = [names[i] for i in np.random.randint(0,len(names),nItems)]
df['openLots'] = np.random.randint(0,100,nItems)
df['occupationRatio'] = np.random.randint(0,100,nItems)
df['DoW'] = [days[i] for i in np.random.randint(0,7,nItems)]
df['Hour'] = np.random.randint(0,12,nItems)




fig = plt.figure(figsize=(12,12))
for index, name in enumerate(names):
    ax = fig.add_subplot(4,6,index+1)
    dfn = df.loc[df.name==name]
    dfn = dfn.groupby(['DoW','Hour']).mean()['occupationRatio'].unstack()
    dfn = dfn.reindex(days)

    # Now we can operate on each plot axis individually
    if index%6!=5: #i.e.
        # Don't draw a colorbar
        sns.heatmap(data = dfn, cmap='coolwarm', ax=ax, cbar=False)
    else:
        sns.heatmap(data = dfn, cmap='coolwarm', ax=ax)

    if index%6!=0:
        # Remove the y-axis label
        ax.set_ylabel('')
        ax.set_yticks(())

    ax.set_title(name)

fig.tight_layout()
fig.show()

结果: enter image description here 您也可以使用x轴(例如删除除底行之外的标签和刻度线)。

答案 1 :(得分:1)

  • 每行只有一次y轴标签(DoW)(最左边的图)
    这可以使用sharey = True作为plt.subplots的参数来完成。
  • 只在每行最右边的地块上设置色彩图传奇(或完全不用,颜色非常自我解释)
    使用cbar = False参数seaborn.heatmap以便不显示颜色条。根据子图的实际数量,这可以作为绘图函数的输入给出。
  • 删除"空图"在最后一行,因为奇数总数
    在创建绘图的循环之后,您可以添加另一个循环来移除未使用的轴。

    for j in range(len(locations), ncols*nrows):
        axs[j].axis("off")
    

这是一个完整的例子(我借用了鳕鱼从@Robbie生成数据帧):

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

days = ['Mon','Tue','Wed','Thurs','Fri','Sat','Sun']
names = ["Parkhaus {:02}".format(i+1) for i in range(22)]

nItems = 1000

df = pd.DataFrame()
df['name'] = [names[i] for i in np.random.randint(0,len(names),nItems)]
df['openLots'] = np.random.randint(0,100,nItems)
df['occupationRatio'] = np.random.rand(nItems)
df['DoW'] = [days[i] for i in np.random.randint(0,7,nItems)]
df['Hour'] = np.random.randint(0,12,nItems)

df2 = df[['name','openLots','occupationRatio','DoW','Hour']]
nrows = 4; ncols=6
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15,9), sharey=True)
axs = axs.flatten()
locations = df2['name'].sort_values().unique()


def occupation_heatmap (name, ax, cbar=False, ylabel=False):
    dfn = df2[df2['name'] == name]
    dfn = dfn.groupby(['DoW', 'Hour']).mean()['occupationRatio'].unstack()
    dfn = dfn.reindex(['Mon', 'Tue', 'Wed','Thu','Fri','Sat','Sun'])
    sns.heatmap(data=dfn, cmap="coolwarm", vmin=0, vmax=1.0, ax=ax, cbar=cbar)
    ax.set_title(name)
    plt.setp(ax.get_yticklabels(), rotation=0)
    if not ylabel: ax.set_ylabel("")


for i, n in enumerate(locations): 
    occupation_heatmap (n, axs[i], cbar=i%ncols==ncols-1, ylabel=i%ncols==0)
for j in range(len(locations), ncols*nrows):
    axs[j].axis("off")

plt.tight_layout()
plt.show()

enter image description here