我有生成四个子图的代码,但是我想通过循环生成那些图表,目前我正在遵循这段代码来生成图表 代码:
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()
答案 0 :(得分:0)
这就是我要做的事情:
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)
这将产生:
这个想法是plt.subplots()
产生一个Axes
对象的数组,因此您可以对其进行循环并在循环中进行绘制。在这种情况下,我需要ndarray.ravel()
,因为axs
是2D数组。
答案 1 :(得分:0)
考虑通过以下方式加强重复代码:
plt.rc
通话中,设置不变的美学效果,例如所有x-ticks和y-ticks字体大小。plt.subplots()
并使用其Axes对象数组。barplot
和lineplot
的ax
参数在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)