1

I just wanted to remove the title of a scatterplot made with seaborn. The title is given by the hue parameter. In this case the title is "Pluton"

x = sns.scatterplot(x="Al total", y="Fe/Fe+Mg", data=df, hue="Pluton", alpha=1)
sns.set_style("ticks")

plt.legend(ncol=3, loc='upper center', 
           bbox_to_anchor=[0.5, 1.25], 
           columnspacing=1.3, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)


plt.ylim(0.2 ,1.1)

Thanks!

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
dinolucas
  • 13
  • 1
  • 3

2 Answers2

2

When you create a scatterplot() with a hue=, or style=, etc., seaborn automatically adds an entry in the legend list to act as a "section header".

Since you are recreating the legend to put it in your desired format, it is pretty trivial to ask matplotlib to exclude the first entry in the legend list to get rid of that "header"

tips = sns.load_dataset('tips')
ax = sns.scatterplot(x="total_bill", y="tip", hue="day",
                     data=tips)
h,l = ax.get_legend_handles_labels()
plt.legend(h[1:],l[1:],ncol=3, loc='upper center', 
           bbox_to_anchor=[0.5, 1.25], 
           columnspacing=1.3, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
0

You can find handles and labels - and remove legend title from both of them. They will be lists, which contain your legend as the first item. For example, labels for your example looks like as:

labels = ['Pluton', 'Desemborque', 'Desemb. (hidrot. I)' ... and all others]

handles will contain similar items but they are represented as matplotlib object:

handles = [<matplotlib.lines.Line2D object at 0x7f114408bf98>, ... and many others]

Code:

import matplotlib.pyplot as plt
import seaborn as sns
# Set style for seaborn
sns.set_style("ticks")

x = sns.scatterplot(x="Al total", y="Fe/Fe+Mg", data=df, hue="Pluton", alpha=1)
# Found handles and labels for legend
ax = x.axes[0][0]
handles, labels = ax.get_legend_handles_labels()
# When set legend in matplotlib use our modified handles and labels
plt.legend(ncol=3, loc='upper center', 
           bbox_to_anchor=[0.5, 1.25], 
           columnspacing=1.3, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True,
           handles=handles[1:], labels=labels[1:],
          )
# Plot
plt.ylim(0.2, 1.1)
plt.show()

Could suggest also read this for other possible approaches

Dmitriy Kisil
  • 2,858
  • 2
  • 16
  • 35