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

2024-06-01 03:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有生成四个子图的代码,但是我想通过循环生成那些图表,目前我正在跟踪这段代码来生成图表 代码:

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

enter image description here


Tags: 代码dfdatasizepltcategorysnspog
2条回答

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

  • 使用^{}调用在一个调用中设置不变的美观,就像所有x-ticks和y-ticks字体大小一样。你知道吗
  • 构建^{}并使用其轴对象数组。你知道吗
  • 使用seaborn的^{}^{}ax参数在轴数组上方循环。你知道吗

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

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

我是这样做的:

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 output

其思想是plt.subplots()生成一个Axes对象数组,这样您就可以在其上循环,并在循环中生成绘图。在这个例子中,我需要ndarray.ravel(),因为axs是一个2D数组。你知道吗

相关问题 更多 >