【问题标题】:How to make Facegrid Countplot hue bars side by side?如何并排制作 Facetgrid Countplot 色调条?
【发布时间】:2018-03-03 11:21:16
【问题描述】:

我正在使用 Facetgrid countplot 绘制打击图。但是,我不能并排制作色调条。

g = sns.FacetGrid(titanic_df, row='Pclass', hue='Survived', size=2, aspect=2.5, sharex=False, sharey=False)
g.map(sns.countplot, 'Tclass', alpha=.6)
g.fig.suptitle('Distribution of Survival by Ticket Prefix and Ticket Class', fontsize=9.5, y=1.01)
g.set_xlabels('Ticket Prefix')
g.fig.text(0, .5, 'Ticket Prefix', va='center', rotation='vertical', fontsize=9.5)
g.add_legend()

所以我尝试使用 Factorplot,它失败了,因为它没有过滤该 Pclass 中不存在的票证前缀 (Tclass)。

g = sns.factorplot(x='Tclass', data=titanic_df, row='Pclass', hue='Survived', kind='count', size=2, aspect=2.5, sharex=False, sharey=False)

我该怎么办? :(

【问题讨论】:

    标签: python pandas matplotlib data-visualization seaborn


    【解决方案1】:

    map_dataframe 是对我有用的技巧。您必须添加当前的调色板作为它的参数。

    g = sns.FacetGrid(titanic_df, row='Pclass', size=2, aspect=2.5, sharex=False, sharey=False)
    g.map_dataframe(sns.countplot, 'Tclass', hue='Survived', palette=sns.color_palette()).add_legend()
    

    【讨论】:

      【解决方案2】:

      factorplot 确实会在其所有子图中使用所有可能的x 值。因此可能需要使用Facetgrid。问题是Facetgridhue 将使每个单独的类别单独绘制在图上,因此条形将重叠。您想要的是使用countplothue 来获取分组条形。那么问题是 hue 参数没有被 map 函数正确识别。所以你可以编写自己的函数来映射,它以hue 作为参数。

      import numpy as np
      import pandas as pd
      import seaborn as sns
      import matplotlib.pyplot as plt
      
      def f(c=1, N=30):
          return pd.DataFrame({"class" : np.ones(N)*c,
                             "survived" : np.random.randint(0,2,size=N),
                             "ticket" : np.random.choice(list("ABCDE")[:c+2], size=N) })
      df = f()
      df = df.append(f(2))
      df = df.append(f(3))    
      
      
      def countplot(x, hue, **kwargs):
          data=kwargs.pop("data")
          order=np.unique(data["ticket"].values)
          sns.countplot(x, hue=hue, data=data,order=order,**kwargs)
      
      g = sns.FacetGrid(df, row='class',  size=2, aspect=2.5, sharex=False, sharey=False)
      g.map_dataframe(countplot, 'ticket',hue='survived', alpha=.6, 
                      palette=sns.color_palette(), )
      
      g.fig.suptitle('Distribution of Survival')
      g.fig.subplots_adjust(top=0.9, left=0.1)
      g.set_xlabels('Ticket Prefix')
      g.add_legend()
      
      plt.show()
      

      【讨论】:

        【解决方案3】:

        我没有设法在 Facetgrid 中做到这一点,但我手动使用 Matplotlib 子图做到了。这不聪明,但至少我得到了我想要的。

        请与我分享实现相同效果的更聪明的方法!谢谢!

        fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=[10,6])
        g1 = sns.countplot(x='Tclass', hue='Survived', data=titanic_df[titanic_df.Pclass == 1], ax=ax1)
        g2 = sns.countplot(x='Tclass', hue='Survived', data=titanic_df[titanic_df.Pclass == 2], ax=ax2)
        g3 = sns.countplot(x='Tclass', hue='Survived', data=titanic_df[titanic_df.Pclass == 3], ax=ax3)
        
        g1.set_title('Pclass = 1', fontsize=9.5, y=.85)
        g2.set_title('Pclass = 2', fontsize=9.5, y=.85)
        g3.set_title('Pclass = 3', fontsize=9.5, y=.85)
        g1.set_xlabel(''); g2.set_xlabel(''); g3.set_xlabel('Ticket Prefix')
        g1.set_ylabel(''); g2.set_ylabel('Frequency'); g3.set_ylabel('')
        g1.legend(''); g3.legend('')
        leg = g2.legend(fontsize='small', loc='center left', bbox_to_anchor=(1, 0.5))
        leg.set_title('Ticket Prefix', prop={'size':'small'})
        fig.suptitle('Distribution of Survival by Ticket Prefix and Ticket Class', fontsize=9.5, y=.94)
        

        【讨论】:

          猜你喜欢
          • 2020-06-23
          • 2016-05-15
          • 1970-01-01
          • 2016-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多