【问题标题】:Seaborn legend modification for multiple overlapping plots多个重叠图的 Seaborn 图例修改
【发布时间】:2021-09-25 13:00:29
【问题描述】:

我正在尝试使用 seaborn swarmplot 为具有两个分类变量(铭牌容量和场景)和一个连续变量(ELCC 值)的数据集创建一个 seaborn 箱线图并覆盖单个数据点。由于我在 seaborn 中有两个重叠图,因此它会为绘制的相同变量生成两个图例。如何在仅显示箱形图中的图例的同时绘制箱形图和群体图。我当前的代码如下所示:

plt.subplots(figsize=(25,18))
sns.set_theme(style = "whitegrid", font_scale= 1.5 )
ax = sns.boxplot(x="Scenario", y="ELCC", hue = "Nameplate Capacity",
                   data=final_offshore, palette = "Pastel1")
ax = sns.swarmplot(x="Scenario", y="ELCC", hue = "Nameplate Capacity", dodge=True, marker='D', size =9, alpha=0.35, data=final_offshore, color="black")

plt.xlabel('Scenarios')
plt.ylabel('ELCC values')
plt.title('Contribution of ad-hoc offshore generator in each scenario')

到目前为止我的情节:

【问题讨论】:

    标签: matplotlib seaborn legend boxplot swarmplot


    【解决方案1】:

    您可以绘制箱形图,获取该图例,绘制群体图,然后重新绘制图例:

    # Draw the bar chart
    ax = sns.boxplot(
        x="Scenario",
        y="ELCC",
        hue="Nameplate Capacity",
        data=final_offshore,
        palette="Pastel1",
    )
    
    # Get the legend from just the box plot
    handles, labels = ax.get_legend_handles_labels()
    
    # Draw the swarmplot
    sns.swarmplot(
        x="Scenario",
        y="ELCC",
        hue="Nameplate Capacity",
        dodge=True,
        marker="D",
        size=9,
        alpha=0.35,
        data=final_offshore,
        color="black",
        ax=ax,
    )
    # Remove the old legend
    ax.legend_.remove()
    # Add just the handles/labels from the box plot back
    ax.legend(
        handles,
        labels,
        loc=0,
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 2021-01-06
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 2013-03-05
      相关资源
      最近更新 更多