首页 > 解决方案 > 如何在循环中为seaborn图表执行子图

问题描述

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

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()

在此处输入图像描述

标签: pythonloopsgraphseaborn

解决方案


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

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是一个二维数组。


推荐阅读