0

我正在使用以下代码行在 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)

其中 pdf 变量是从列表构造的熊猫数据框。

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

任何想法,我怎么能一个接一个地画它们?我究竟做错了什么?

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

4

2 回答 2

0

你试过子图吗?

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,允许更多地自定义位置和大小。

于 2015-06-19T15:22:41.000 回答
0

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

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

  2. 我有“国家名称”作为 x 标签。一些国家/地区名称很长,例如“阿拉伯联合酋长国”,因此为避免重叠,我使用 90 度的旋转角度。当我使用 将图表绘制在单独的行上时f, (ax1, ax2, ax3) = plt.subplots(3,1, figsize=(15,6)),我得到了 x 标签与下图的重叠。但是如果我为每个图使用单独的 subplot() 语句,则没有重叠。因此最终代码如下所示

    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)
    
于 2015-06-21T18:03:33.603 回答