首页 > 解决方案 > 在循环内增加 plt.subplot() 中绘图的 h 大小 - Python

问题描述

我有这个代码:

for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
    plt.subplot(1,2,1)
    sns.boxplot(x=i, y="Y", data=df)

    plt.subplot(1,2,2)
    sns.boxplot(x=i, y="Temp", data=df)

    plt.tight_layout()
    plt.show()

它给了我我需要的所有情节。这是一次性循环:

情节

如您所见,它们x axis是重叠的,我正在尝试增加每个绘图的水平尺寸以获得更好的可视化效果。

标签: pythonmatplotlibseaborn

解决方案


您受到图形宽度的限制。figsize您可以使用该属性使您的身材更宽。您可以通过显式定义 ( plt.figure) 或获取当前图形 ( plt.gcf) 来“抓取”您的图形。

但是,我更喜欢使用plt.subplots来定义图形和轴:

for i in ["Dia", "DiaSemana", "Mes", "Año", "Feriado"]:
    fig, axes = plt.subplots(ncols=2, figsize=(15, 5))  # set width of figure and define both figure and axes
    sns.boxplot(x=i, y="Y", data=df, ax=axes[0])
    sns.boxplot(x=i, y="Temp", data=df, ax=axes[1])

    plt.tight_layout()
    plt.show()

或者,您可以减少 x 轴上的刻度数。


推荐阅读