Matplotlib: text color of the legend matching the symbol in the scatter graph

I made a scatter plot with three different colors, and I want to combine the color of the symbol and text in the legend.

For the case of line graphs, there is a pleasant solution :

leg = ax.legend() # change the font colors to match the line colors: for line,text in zip(leg.get_lines(), leg.get_texts()): text.set_color(line.get_color()) 

However, scatter colors cannot be accessed using get_lines() . For the case of 3 colors, I think that I can manually set the text colors one by one, for example, for example. text.set_color('r') . But I was curious if this could be done automatically, like lines. Thanks!

+5
source share
2 answers

It seems complicated, but gives you what you want. Suggestions are welcome. I use ax.get_legend_handles_labels() to get the markers and use tuple(handle.get_facecolor()[0]) to get the matplotlib color tuple. Made an example with a really simple diffused pattern:

Edit:

As ImportanceOfBeingErnest pointed out in the answer:

  • leg.legendHandles will return legend handles;
  • A list, instead of a tuple, can be used to assign matplotlib color.

Codes are simplified as:

 import matplotlib.pyplot as plt from numpy.random import rand fig, ax = plt.subplots() for color in ['red', 'green', 'blue']: x, y = rand(2, 10) ax.scatter(x, y, c=color, label=color) leg = ax.legend() for handle, text in zip(leg.legendHandles, leg.get_texts()): text.set_color(handle.get_facecolor()[0]) plt.show() 

I got: enter image description here

0
source

Scatter borders have facecolor and edgecolor. The legend handler for the scatter is PathCollection .

Thus, you can iterate over the legend descriptors and set the text color in the facecolor of the legend descriptor

 for h, t in zip(leg.legendHandles, leg.get_texts()): t.set_color(h.get_facecolor()[0]) 

Full code:

 import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() for i in range(3): x,y = np.random.rand(2, 20) ax.scatter(x, y, label="Label {}".format(i)) leg = ax.legend() for h, t in zip(leg.legendHandles, leg.get_texts()): t.set_color(h.get_facecolor()[0]) plt.show() 

enter image description here

+4
source

Source: https://habr.com/ru/post/1268760/


All Articles