繁体   English   中英

如何在 seaborn 图表的循环中执行子图

[英]how to perform subplot in loop for seaborn charts

我有生成四个子图的代码,但我想通过循环生成这些图表,目前我正在按照这段代码生成图表代码:

plt.figure(figsize=(20, 12))
plt.subplot(221)
sns.barplot(x = 'Category', y = 'POG_Added', data = df)
xticks(rotation = 90)
plt.xticks(size = 11)
plt.yticks(size = 11)
plt.xlabel("Category",size = 13)
plt.ylabel("POG_Added",size = 13)

plt.subplot(222)
sns.barplot(x = 'Category', y = 'Live_POG', data = df)
xticks(rotation = 90)
plt.xticks(size = 11)
plt.yticks(size = 11)
plt.xlabel("Category",size = 13)
plt.ylabel("Live_POG",size = 13)

plt.subplot(223)
sns.lineplot(x = 'Category', y = 'D01_CVR', data = df)
#sns.barplot(x = 'Category', y = 'D2-08-Visits', data = df,label='D2-08_Visits')
xticks(rotation = 90)
plt.xticks(size = 11)
plt.yticks(size = 11)
plt.xlabel("Category",size = 13)
plt.ylabel("D01_CVR",size = 13)

plt.subplot(224)

plt.xticks(rotation='vertical')
ax = sns.barplot(x='Category',y='D2-08-Units',data=df)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), df["D01_CVR"], alpha = .75, color = 'r')

plt.subplots_adjust(hspace=0.55,wspace=0.55)
plt.show()

在此处输入图像描述

以下是我如何做这样的事情:

import numpy as np
import matplotlib.pyplot as plt

data = [np.random.random((10, 10)) for _ in range(6)]

fig, axs = plt.subplots(ncols=3, nrows=2, figsize=(9, 6))
for ax, dat in zip(axs.ravel(), data):
    ax.imshow(dat)

这会产生:

matplotlib 输出

这个想法是plt.subplots()产生一个Axes对象数组,所以你可以循环它并在循环中制作你的图。 在这种情况下,我需要ndarray.ravel()因为axs是一个二维数组。

考虑通过以下方式收紧重复代码:

  • 使用plt.rc调用在一次调用中设置所有 x-ticks 和 y-ticks 字体大小等不变的美学。
  • 构建plt.subplots()并使用其 Axes 对象数组。
  • 使用 seaborn 的barplotlineplotax参数在 Axes 数组上方循环。

虽然考虑到特殊的两个地块并没有完全干燥,但以下是调整:

# AXES AND TICKS FONT SIZES
plt.rc('xtick', labelsize=11)
plt.rc('ytick', labelsize=11)
plt.rc('axes', labelsize=13)

# FIGURE AND SUBPLOTS SETUP
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 12))

# BAR PLOTS (FIRST ROW)
for i, col in enumerate(['POG_Added', 'Live_POG']):
    sns.barplot(x='Category', y=col, data=df, ax=axes[0,i])
    axes[0,i].tick_params(axis='x', labelrotation=90)

# LINE PLOT 
sns.lineplot(x='Category', y='D01_CVR', data=df, ax=axes[1,0])
axes[1,0].tick_params(axis='x', labelrotation=90)

# BAR + LINE DUAL PLOT
sns.barplot(x='Category', y='D2-08-Units', data=df, ax=axes[1,1])
ax2 = axes[1,1].twinx()
ax2.plot(axes[1,1].get_xticks(), df["D01_CVR"], alpha = .75, color = 'r')
axes[1,1].tick_params(axis='x', labelrotation=90)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM