1

I'm trying to get the text in my legend to match the color of the lines from the plot. There is a nice summary of how to do this by Dan, over here: Matplotlib: Color-coded text in legend instead of a line

However, it does not seem to work for errorbar plot types. Does anyone have an idea of what handle I should use to make this change?

Here's some example code that shows how it works with the plot type element, but doesn't work with the errorbar type element:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.1,4,0.5)
y1 = np.exp(-x)
y2 = np.exp(-x)*1.2+0.25

plot = plt.figure()
ax = plot.add_axes([0,0,1,1])

ax.plot(x,y1,color="red",label="Y1")
ax.errorbar(x,y2,yerr=0.1,color="blue",marker='*',capsize=4,label="Y2")

leg = ax.legend();

for line, text in zip(leg.get_lines(), leg.get_texts()):
       text.set_color(line.get_color())

And here's an example of how that plot looks:

Code will change text color of plot types but not errorbar types

Thanks for any advice!

1 Answer 1

2

The .get_lines() method gives you the lines in the legend.

[h for h in self.legendHandles if isinstance(h, Line2D)]

The errorbar is not a Line2D. So in principle you could instead iterate over leg.legendHandles. The problem is then that colors are not well specified. They may be names or arrays. This needs to be taken care of such that the solution becomes a bit more complicated.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.1,4,0.5)
y1 = np.exp(-x)
y2 = np.exp(-x)*1.2+0.25

plot = plt.figure()
ax = plot.add_axes([0,0,1,1])

ax.plot(x,y1,color="red",label="Y1")
ax.errorbar(x,y2,yerr=0.1,color="blue",marker='*',capsize=4,label="Y2")

leg = ax.legend();

for artist, text in zip(leg.legendHandles, leg.get_texts()):
    col = artist.get_color()
    if isinstance(col, np.ndarray):
        col = col[0]
    text.set_color(col)

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

I also provided an even more general solution to the linked question.
Perfect, this is exactly what I was hoping for. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.