Home > database >  Marker style of legend and the graph are not matching?
Marker style of legend and the graph are not matching?

Time:01-27

Below is the code I am using for generating the plot, but the issue is style of the marker in the graph is different from that of the plot

sns.set_style(rc={'boxplot.flierprops.markeredgecolor':'black' ,'boxplot.flierprops.markeredgewidth':1.25,'boxplot.flierprops.markerfacecolor':'white'})
fig, scatter = plt.subplots(figsize = (6,4), dpi = 100)
scatter = sns.lineplot(data=df_whole,x='shortest_distance',y='similarity',style ='Metric',hue='Metric'
                       ,markers=True,lw=1,markeredgewidth=1.25,markeredgecolor='black',markersize=7,dashes= False,errorbar=None,markerfacecolor='white')
scatter.set(title='TF-IDF')
scatter.legend(title = "Similarity Methods",prop={'size': 12})

graph

CodePudding user response:

As seaborn uses complex combinations of matplotlib elements to create its plots, and tries to make the legend as compact as possible, the legend is often custom-made. As such, seaborn unfortunately does not always take into account all matplotlib-level parameters.

In this case, the problem can be worked around via assigning these parameters again to the legend handles. Here is an example using one of seaborn's test datasets:

import matplotlib.pyplot as plt
import seaborn as sns

flights = sns.load_dataset('flights')
markerprops = dict(markeredgewidth=1.25, markeredgecolor='black', markersize=7, markerfacecolor='none')
ax = sns.lineplot(data=flights, x='year', y='passengers', style='month', hue='month',
                  markers=True, lw=1, dashes=False, errorbar=None, **markerprops)
ax.set(title='TF-IDF')
handles, labels = ax.get_legend_handles_labels()
for h in handles:
    h.set(**markerprops)
ax.legend(handles=handles, title="Months", prop={'size': 12}, ncol=3)
plt.tight_layout()
plt.show()

sns.lineplot with updated markers in the legend

PS: Matplotlib functions usually return the graphical elements they created (e.g. scatter dots or lines), while seaborn (and pandas) usually returns the subplot (ax) or grid of subplots. As such, giving the name scatter to the return value of sns.lineplot might be confusing when comparing code with other matplotlib and seaborn examples.

  • Related