Phyinmi Phyinmi -4 years ago 232
Python Question

matplotlib: match legend text color with symbol in scatter plot

I made a scatter plot with 3 different colors and I want to match the color of the symbol and the text in the legend.

A nice solution exist for the case of line plots:

leg = ax.legend()

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

However, scatter plot colors cannot be accessed by
.For the case of 3 colors I think I can manually set the text colors one-by-one using eg.
. But I was curious if it can be done automatically as lines. Thanks!

Answer Source

This seems complicated but does give you what you want. Suggestions are welcomed. 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 scatter plot like this:


As ImportanceOfBeingErnest pointed in his answer:

  1. leg.legendHandles will return the legend handles;
  2. List, instead of 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()):

What I got is: enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download