matplotlib画子图: plt.subplot 与 plt.subplots

在一张画布上画多个子图, 尝试两种方式:

  • plt.subplots(nrows, ncols) 子图需要一个一个的指定
  • plt.subplot(nrows, ncols, i) 子图可以使用for循环

一. plt.subplots()

fig, axes = plt.subplots(nrows = 3, ncols = 2, figsize = (12, 12))
sns.boxplot(data = data, y = 'count', orient = 'v', ax = axes[0][0])
sns.boxplot(data = data, y = 'count', x = 'season',     orient = 'v', ax = axes[0][1])
sns.boxplot(data = data, y = 'count', x = 'hour',       orient = 'v', ax = axes[1][0])
sns.boxplot(data = data, y = 'count', x = 'workingday', orient = 'v', ax = axes[1][1])
sns.boxplot(data = data, y = 'count', x = 'month',      orient = 'v', ax = axes[2][0])
sns.boxplot(data = data, y = 'count', x = 'weather',    orient = 'v', ax = axes[2][1])

axes[0, 0].set(ylabel = 'Count', title = 'Box Plot On Count')
axes[0, 1].set(ylabel = 'Count', xlabel = 'Season',     title = 'Box Plot On Count Acorss Season')
axes[1, 0].set(ylabel = 'Count', xlabel = 'Hour',       title = 'Box Plot On Count Acorss Season')
axes[1, 1].set(ylabel = 'Count', xlabel = 'WorkingDay', title = 'Box Plot On Count Acorss Season')
axes[2, 0].set(ylabel = 'Count', xlabel = 'Month',      title = 'Box Plot On Count Acorss Season')
axes[2, 1].set(ylabel = 'Count', xlabel = 'Weahter',    title = 'Box Plot On Count Acorss Season',
              xticklabels = ['Clear','Mist','Light Snow','Heavy Rain'])
plt.tight_layout()

matplotlib画子图: plt.subplot 与 plt.subplots_第1张图片

二. plt.subplot()

def sns_boxplot(df, x_list, y, nrows, ncols):
    plt.figure(figsize = (ncols*6, nrows*4))
    i = 1
    for x in x_list:
        plt.subplot(nrows, ncols, i)
        sns.boxplot(data = df, x = x, y = y, orient = 'v')
        plt.ylabel(y.capitalize(), fontsize = 14)
        if not x:
            plt.title('Box Plot On Count', fontsize = 14)
        else:
            plt.title('Box Plot On Count Across '+ x.capitalize(), size = 14)
            plt.xlabel(x.capitalize(), fontsize = 12)
        i += 1
    plt.tight_layout()

x_list = [None, 'season', 'hour', 'workingday', 'month', 'weather']
sns_boxplot(data, x_list, 'count', len(x_list)*0.5, 2)

matplotlib画子图: plt.subplot 与 plt.subplots_第2张图片

你可能感兴趣的:(模板,python)