python matplotlib Drawing Realizes the Operation of Deleting Repeated Redundant Legend

  • 2021-10-27 08:08:30
  • OfStack

Question:

Because when I do my own project, I need to draw data cyclically. Suppose there are 100 samples, and each sample contains two coordinate points (A, B). I need to mark these two points with different colors and draw the connection between the two points at the same time.

Obviously, I only need three (A points, B points, AB connections) in this question, instead of 300, because A points of each sample are all of the same color, B points are also of one color, and so are AB connections.

But simply use plt. legend () after drawing, and it will give you all 300 legends, which is definitely not what I want.

Exploration process:

How to solve it?

Of course, there is a very mandatory method, that is, only when drawing the first sample or the last sample, assign label to it, and when other samples are not given label, they will not be drawn.

But I wonder if there is a better way. Baidu has been exhausting all keywords for a long time, but there is no result.

Turning to Google, Thinking about changing keywords into English (I used to think that reading English blogs would be much slower than Chinese blogs, I always prefer to read in my mother tongue, But this experience will probably change my attitude later. Compared with the long time spent to exclude a large number of irrelevant answers from Baidu, It seems that it is not as efficient as searching English directly. The keyword search is: python omit redundant legend). As a result, the first search result saw the solution I want, which is very surprising. It is convenient for me to find it later and for people who encounter the same problem. Therefore, it is recorded, although it is not a multi-God thing.

Solution:


from collections import OrderedDict
import matplotlib.pyplot as plt
 
handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

Understand:

The legend function of plt takes two arguments, one is the handles list and one is the label list.

The purpose of introducing the ordered dictionary OrderedDict is to remove redundant legends, because the key values of the dictionary cannot be repeated (that is, only one duplicate is reserved).

Line 1 should iteratively return all handles and labels stored in the current plt to handles variables and labels variables. Every step you drew on the canvas before should be stored in plt.

Therefore, the function of the above code is to keep only all legend names that do not have the same name in plt, and no duplicate legend names appear

Supplement: Empty drawing of Python/matplotlib

clf() # Clear map

cla() # Clear Axis

close() # Close the window


Related articles: