Issue
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?
Solution
Credits to @MisterMiyagi for helping me out
I had two errors in my code:
- I used both
plt.legend
andax.legend
, so they overlapped each other - However that still doesn't fix the problem, I also had to make sure when running
ax.legend
, it had to be in one command, not multiple as they would override each other!
This will work:
def func():
...
# revome duplicate legends
legend(ax)
# 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), loc='center left', bbox_to_anchor=(1, 0.5))
Answered By - DialFrost
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.