1

我正在尝试使用 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')

到目前为止我的情节: 箱线图+群图

4

1 回答 1

0

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

# 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,
)
于 2021-07-16T20:51:09.667 回答