seaborn barplot() 输出图形被覆盖

seaborn barplot() output figure is overwritten

我正在使用以下代码行在 jupyter 笔记本中绘制几个 seaborn 条形图

sns.set(style="darkgrid")
rcParams['figure.figsize'] = (12, 8)
bar_plot = sns.barplot(x='Country',y='Average Rate',data=pddf1, palette="muted", x_order=pddf1["Country"].tolist())
abc = bar_plot.set_xticklabels(pddf1["Country"],rotation=90)

sns.set(style="darkgrid")
rcParams['figure.figsize'] = (12, 4)
bar_plot = sns.barplot(x='Country',y='% Jobs Completed',data=pddf2,     palette="muted", x_order=pddf2["Country"].tolist())
abc = bar_plot.set_xticklabels(pddf2["Country"],rotation=90)

其中 pddf 变量是从列表构建的熊猫数据帧。

如果我注释掉一组语句,则另一组图绘制正确。但是,如果它们都 运行 在一起,则两个图形都绘制在相同的轴上。换句话说,第一个被第二个覆盖。我确定,因为我在最终图中看到了第一张图中较长的条形图。

知道吗,我怎样才能一个接一个地画出它们?我做错了什么?

由于seaborn是在matplotlib之上开发的,所以我也搜索了一下。在 matplotlib 中,您可以通过更改图形编号来绘制。不确定是否可以在 seaborn 中使用 rcParams 实现。

你试过次要情节吗?

sns.set(style="darkgrid")   # Only need to call this once 
fig, (ax1,ax2) = plt.subplots(1,2, figsize=(12,8))  # plots on same row
sns.barplot(x='Country',y='Average Rate',data=pddf1, palette="muted", x_order=pddf1["Country"].tolist(), ax=ax1)
ax1.set_xticklabels(pddf1["Country"],rotation=90)

sns.barplot(x='Country',y='% Jobs Completed',data=pddf2,     palette="muted", x_order=pddf2["Country"].tolist(), ax=ax2)
abc = bar_plot.set_xticklabels(pddf2["Country"],rotation=90)

这会产生两个大小相同的数字;还有其他选项,例如 gridspec,允许更多自定义位置和大小。

感谢@iayork 的子图()。我只想指出一些可能对其他人有帮助的事情

  1. 我实际上有 3 个数字可以绘制并且将在不同的行上使用它们,否则它们会变得太小而无法查看

  2. 我有 "country name" 作为 x 标签。有些国家名称很长,如 "United Arab Emirates",因此为了避免重叠,我使用 90 度的旋转角度。当我使用 f, (ax1, ax2, ax3) = plt.subplots(3,1, figsize=(15,6)) 在单独的行上绘制图形时,我得到 x 标签与图形的重叠以下。但是如果我对每个图使用单独的 subplot() 语句,就没有 overlap.Hence 最终代码看起来像这样

    f, (ax1) = plt.subplots(1,figsize=(15,6))
    f, (ax2) = plt.subplots(1,figsize=(15,6))
    f, (ax3) = plt.subplots(1,figsize=(15,6))
    
    sns.set(style="darkgrid")
    
    sns.barplot(x='Country',y='Average Rate',data=pddf1, palette="muted", x_order=pddf1["Country"].tolist(), ax=ax1)
    ax1.set_xticklabels(pddf1["Country"],rotation=90)
    
    sns.barplot(x='Country',y='Jobs Completed',data=pddf2, palette="muted", x_order=pddf2["Country"].tolist(), ax=ax2)
    ax2.set_xticklabels(pddf2["Country"],rotation=90)
    
    sns.barplot(x='Country',y='User Rating',data=pddf3, palette="muted", x_order=pddf3["Country"].tolist(), ax=ax3)
    ax3.set_xticklabels(pddf3["Country"],rotation=90)