【问题标题】:How do I plot two countplot graphs side by side in seaborn?如何在 seaborn 中并排绘制两个计数图?
【发布时间】:2017-08-25 04:05:05
【问题描述】:

我正在尝试绘制两个计数图来显示击球次数和保龄球次数。我尝试了以下代码:

l=['batting_team','bowling_team']
for i in l:
    sns.countplot(high_scores[i])
    mlt.show()

但是通过使用这个,我得到了两个图,一个在另一个之下。我怎样才能让它们并排订购?

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:
    import matplotlib.pyplot as plt
    l=['batting_team', 'bowling_team']
    figure, axes = plt.subplots(1, 2)
    index = 0
    for axis in axes:
      sns.countplot(high_scores[index])
      index = index+1
    plt.show()
    

    【讨论】:

      【解决方案2】:

      类似这样的:

      import seaborn as sns
      import pandas as pd
      import matplotlib.pyplot as plt
      
      batData = ['a','b','c','a','c']
      bowlData = ['b','a','d','d','a']
      
      df=pd.DataFrame()
      df['batting']=batData
      df['bowling']=bowlData
      
      
      fig, ax =plt.subplots(1,2)
      sns.countplot(df['batting'], ax=ax[0])
      sns.countplot(df['bowling'], ax=ax[1])
      fig.show()
      

      这个想法是在图中指定子图 - 有很多方法可以做到这一点,但上面的方法可以正常工作。

      【讨论】:

      • 看看没有seaborn的更通用的解决方案:stackoverflow.com/a/54266570/5084355
      • 为什么我得到 4 张图片?两张图片是空的,另外两张有我想要的图表。
      • @cyber-math 代码只生成两个子图,也许您输入了类似:plt.subplots(2,2)?你试过运行这个确切的脚本吗?
      • 感谢您的回复。这是我所做的 fig, ax =plt.subplots(1,2) sns.catplot(x='CDR',y='Age',data=long_df, ax=ax[0]) sns.catplot(x='CDR',y='MMSE',data=long_df, ax=ax[1]) 删除 sharey
      • 我之前遇到过这个额外的空白情节问题,plt.close() 在那段时间工作。现在它不工作了。