【问题标题】:Move seaborn plot legend to a different position将 seaborn 情节图例移动到不同的位置
【发布时间】:2015-01-17 02:28:31
【问题描述】:

我正在使用 factorplot(kind="bar") 和 seaborn。

情节很好,只是图例放错了位置:太靠右了,文字超出了情节的阴影区域。

如何让 seaborn 将图例放置在其他位置,例如左上角而不是右中角?

【问题讨论】:

  • 对于seaborn >= 0.11.2,使用.move_legend,如answer所示

标签: python matplotlib seaborn


【解决方案1】:

基于@user308827 的回答:您可以在factorplot 中使用legend=False 并通过matplotlib 指定图例:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")
  • plt 作用于当前轴。要从 FacetGrid 获取轴,请使用图。
    • g.fig.get_axes()[0].legend(loc='lower left')

【讨论】:

    【解决方案2】:

    在此处查看文档:https://matplotlib.org/users/legend_guide.html#legend-location

    添加这个只是为了将传奇带出情节:

    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

    【讨论】:

      【解决方案3】:

      修改示例here

      你可以使用legend_out = False

      import seaborn as sns
      sns.set(style="whitegrid")
      
      titanic = sns.load_dataset("titanic")
      
      g = sns.factorplot("class", "survived", "sex",
                          data=titanic, kind="bar",
                          size=6, palette="muted",
                         legend_out=False)
      g.despine(left=True)
      g.set_ylabels("survival probability")
      

      【讨论】:

        【解决方案4】:

        这就是我能够将图例移动到绘图内的特定位置并更改绘图的方面和大小的方法:

        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        matplotlib.style.use('ggplot')
        import seaborn as sns
        sns.set(style="ticks")
        
        figure_name = 'rater_violinplot.png'
        figure_output_path = output_path + figure_name
        
        viol_plot = sns.factorplot(x="Rater", 
                               y="Confidence", 
                               hue="Event Type", 
                               data=combo_df, 
                               palette="colorblind",
                               kind='violin',
                               size = 10,
                               aspect = 1.5,
                               legend=False)
        
        viol_plot.ax.legend(loc=2)
        viol_plot.fig.savefig(figure_output_path)  
        

        这对我来说改变了情节的大小和方面以及将图例移到情节区域之外。

        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        matplotlib.style.use('ggplot')
        import seaborn as sns
        sns.set(style="ticks")
        
        
        figure_name = 'rater_violinplot.png'
        figure_output_path = output_path + figure_name
        
        viol_plot = sns.factorplot(x="Rater", 
                               y="Confidence", 
                               hue="Event Type", 
                               data=combo_df, 
                               palette="colorblind",
                               kind='violin',
                               size = 10,
                               aspect = 1.5,
                               legend_out=True)
        
        viol_plot.fig.savefig(figure_output_path)  
        

        我从 mwaskom 的回答 here 和 Fernando Hernandez 的回答 here 中发现了这一点。

        【讨论】:

          【解决方案5】:
          import matplotlib.pyplot as plt
          import seaborn as sns
          
          # load the data
          penguins = sns.load_dataset('penguins', cache=False)
          

          人物水平图

          g = sns.displot(penguins, x="bill_length_mm", hue="species", col="island", col_wrap=2, height=3)
          sns.move_legend(g, "upper left", bbox_to_anchor=(.55, .45), title='Species')
          plt.show()
          

          轴水平图

          ax = sns.histplot(penguins, x="bill_length_mm", hue="species")
          sns.move_legend(ax, "lower center", bbox_to_anchor=(.5, 1), ncol=3, title=None, frameon=False)
          plt.show()
          

          【讨论】:

            【解决方案6】:

            看来你可以直接调用:

            g = sns.factorplot("class", "survived", "sex",
                            data=titanic, kind="bar",
                            size=6, palette="muted",
                           legend_out=False)
            
            g._legend.set_bbox_to_anchor((.7, 1.1))
            

            【讨论】:

              【解决方案7】:

              如果您想自定义您的图例,只需使用add_legend 方法。它采用与 matplotlib plt.legend 相同的参数。

              import seaborn as sns
              sns.set(style="whitegrid")
              
              titanic = sns.load_dataset("titanic")
              
              g = sns.factorplot("class", "survived", "sex",
                                  data=titanic, kind="bar",
                                  size=6, palette="muted",
                                 legend_out=False)
              g.despine(left=True)
              g.set_ylabels("survival probability")
              g.add_legend(bbox_to_anchor=(1.05, 0), loc=2, borderaxespad=0.)
              

              【讨论】:

              • 这似乎创造了一个新的传奇。在我的代码中,我还有其他行来调整图例(标题、大小和透明度..)。如果我调用它来调整位置,那么以下几行不起作用......
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-08-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-11-05
              相关资源
              最近更新 更多