【问题标题】:Seaborn boxplot + stripplot: duplicate legendSeaborn boxplot + stripplot:重复的图例
【发布时间】:2016-06-03 00:11:46
【问题描述】:

seaborn 中最酷的东西之一是 boxplot + stripplot 组合:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

tips = sns.load_dataset("tips")

sns.stripplot(x="day", y="total_bill", hue="smoker",
data=tips, jitter=True,
palette="Set2", split=True,linewidth=1,edgecolor='gray')

sns.boxplot(x="day", y="total_bill", hue="smoker",
data=tips,palette="Set2",fliersize=0)

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

不幸的是,正如您在上面看到的,它产生了双重图例,一个用于箱线图,一个用于条形图。显然,它看起来很荒谬和多余。但我似乎找不到摆脱stripplot 传奇的方法,只留下boxplot 传奇。也许,我可以以某种方式从plt.legend 中删除项目,但我在文档中找不到它。

【问题讨论】:

    标签: python matplotlib legend seaborn


    【解决方案1】:

    在实际绘制图例本身之前,您可以在图例中get what handles/labels should exist。然后,您只使用您想要的特定图例绘制图例。

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    tips = sns.load_dataset("tips")
    
    sns.stripplot(x="day", y="total_bill", hue="smoker",
    data=tips, jitter=True,
    palette="Set2", split=True,linewidth=1,edgecolor='gray')
    
    # Get the ax object to use later.
    ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
    data=tips,palette="Set2",fliersize=0)
    
    # Get the handles and labels. For this example it'll be 2 tuples
    # of length 4 each.
    handles, labels = ax.get_legend_handles_labels()
    
    # When creating the legend, only use the first two elements
    # to effectively remove the last two.
    l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    

    【讨论】:

      【解决方案2】:

      我想补充一点,如果您使用子图,图例处理可能会有点问题。顺便说一下,上面的代码给出了一个非常好的数字(@Sergey Antopolskiy 和@Ffisegydd),它不会在子图中重新定位图例,它一直很顽固地出现。请参阅上面适用于子图的代码:

      import matplotlib.pyplot as plt
      import seaborn as sns
      import pandas as pd
      
      tips = sns.load_dataset("tips")
      
      fig, axes = sns.plt.subplots(2,2)
      
      sns.stripplot(x="day", y="total_bill", hue="smoker",
                    data=tips, jitter=True, palette="Set2", 
                    split=True,linewidth=1,edgecolor='gray', ax = axes[0,0])
      
      ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
                       data=tips,palette="Set2",fliersize=0, ax = axes[0,0])
      
      handles, labels = ax.get_legend_handles_labels()
      
      l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
      

      原来的传说仍然存在。为了擦除它,您可以添加以下行:

      axes[0,0].legend(handles[:0], labels[:0])
      

      编辑:在最新版本的 seaborn (>0.9.0) 中,这通常会在角落中留下一个小白框,如 cmets 所示。要解决它,请使用the answer in this post:

      axes[0,0].get_legend().remove()
      

      【讨论】:

      • 在seaborn 0.9.0 中,这会在第一个图中为空图例留下一个小白框。
      猜你喜欢
      • 2021-11-17
      • 2021-10-20
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2019-04-07
      • 2021-10-29
      相关资源
      最近更新 更多