【发布时间】:2023-01-29 22:48:52
【问题描述】:
我有一个函数可以在两列中并排绘制箱线图和直方图。我想更改我的代码以使其成为 4 列以缩短输出。我玩过代码,但遗漏了一些东西。我可以将它更改为 4 列,但是右边的 2 列是空白的,所有内容都在左边的两列中。
我尝试将行更改为
ax_box, ax_hist, ax_box2, ax_hist2 = axs[i*ncols], axs[i*ncols+1], axs[i*ncols+2], axs[i*ncols+3]
代替
ax_box, ax_hist = axs[i*ncols], axs[i*ncols+1]
在更改列索引的其他迭代中。 我是 python 的新手,我知道我遗漏了一些对更有经验的人来说显而易见的东西。
我的代码是:
`def hist_box_all1(data, bins):
ncols = 2 # Number of columns for subplots
nrows = len(data.columns) # Number of rows for subplots
height_ratios = [0.75, 0.75] * (nrows // 2) + [0.75] * (nrows % 2)
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15,4*nrows), gridspec_kw={'height_ratios': height_ratios})
axs = axs.ravel() # Flatten the array of axes
for i, feature in enumerate(data.columns):
ax_box, ax_hist = axs[i*ncols], axs[i*ncols+1]
sns.set(font_scale=1) # Set the size of the label
x = data[feature]
n = data[feature].mean() # Get the mean for the legend
m=data[feature].median()
sns.boxplot(
x=x,
ax=ax_box,
showmeans=True,
meanprops={
"marker": "o",
"markerfacecolor": "white",
"markeredgecolor": "black",
"markersize": "7",
},
color="teal",
)
sns.histplot(
x=x,
bins=bins,
kde=True,
stat="density",
ax=ax_hist,
color="darkorchid",
edgecolor="black",
)
ax_hist.axvline(
data[feature].mean(), color="teal", label="mean=%f" % n
) # Draw the mean line
ax_hist.axvline(
data[feature].median(), color="red", label="median=%f" % m
) #Draw the median line
ax_box.set(yticks=[]) # Format the y axis label
#sns.despine(ax=ax_hist) # Remove the axis lines on the hist plot
#sns.despine(ax=ax_box, left=True) # Remove the axis lines on the box plot
ax_hist.legend(loc="upper right") # Place the legend in the upper right corner
plt.suptitle(feature)
plt.tight_layout()`
【问题讨论】:
标签: python matplotlib multiple-columns subplot