1

I am trying to create a seaborn boxplot and overlay with individual data points using seaborn swarmplot for a dataset that has two categorical variables (Nameplate Capacity and Scenario) and one continuous variable (ELCC values). Since I have two overlaying plots in seaborn, it is generating two legends for the same variables being plotted. How do I plot a box plot along with a swarm plot while only showing the legend from the box plot. My current code looks like:

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')

My plot so far: Boxplot+swarm plot

Alex
  • 6,610
  • 3
  • 20
  • 38
pandi20
  • 11
  • 1
  • 5

1 Answers1

0

You can draw your box plot, get that legend, draw the swarm plot and then re-draw the legend:

# 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,
)
Alex
  • 6,610
  • 3
  • 20
  • 38