Issue
I struggle finding a way of properly displaying only the labels respective to the markers in a scatterplot. My code looks as follows:
fig, ax = plt.subplots(1,1)
plot_white = sns.scatterplot(data=df_white, x='EngCorr_Player', y='EngCorr_Opponent', hue='Elo_Opponent', ax=ax, marker='D', label='White')
plot_black = sns.scatterplot(data=df_black, x='EngCorr_Player', y='EngCorr_Opponent', hue='Elo_Opponent', ax=ax, marker='X', s=140, label='Black')
ax.legend()
plt.show()
The problem here, is that the variable for the hue is included in the legend. Plot 1
If I instead try to specify the labels when calling the legend, the marker of the second plot is wrong (circle, instead of star). Plot 2
ax.legend(labels=['White', 'Black'])
And if I specify the handles, with
ax.legend(handles=[plot_white, plot_black], labels=['White', 'Black'])
An empty legend is displayed and the error message "UserWarning: Legend does not support <AxesSubplot:xlabel='EngCorr_Player', ylabel='EngCorr_Opponent'> instances. A proxy artist may be used instead." appears.
I tried to look into artists but don't grasp anything.
Solution
See if this what you are looking for... It is similar to what you have. Except that you get the handles and text of the legend using ax.get_legend_handles_labels()
, then keep only those with names White and Black and then call ax.legend()
fig, ax = plt.subplots(1,1)
ax = sns.scatterplot(data=df_white, x='EngCorr_Player', y='EngCorr_Opponent', hue='Elo_Opponent', ax=ax, marker='D', label='White')
ax = sns.scatterplot(data=df_black, x='EngCorr_Player', y='EngCorr_Opponent', hue='Elo_Opponent', ax=ax, marker='X', s=140, label='Black')
hand, labl = ax.get_legend_handles_labels()
handout=[]
lablout=[]
for h,l in zip(hand,labl):
if l in ['White', 'Black']:
lablout.append(l)
handout.append(h)
ax.legend(handout, lablout)
plt.show()
Answered By - Redox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.