I have seen many good questions questions and answers, but I am not sure how to combine two of them:
These two questions have great answers, but I am unable to do both at the same time! Putting both code into a single function doesn't work:
def func():
...
# revome duplicate legends
legend(ax)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# remove duplicate legends
def legend(ax):
handles, labels = ax.get_legend_handles_labels()
unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]
ax.legend(*zip(*unique))
I tried putting the code plt.legend(...)
before and after legend(ax)
:
Putting the remove duplicate function before moving it outside of the plot area results in the legend being moved outside of the plot area, but does not remove any duplicate legends:
Removing the duplicate legends before moving the legends outside of the plot area for some reason also does not move the legend out of the plot area, but it removes the duplicate legends!
How do I fix this to not only move the legend out of the plot area, and remove any duplicate legends?