简体   繁体   中英

matplotlib get errorbar color from legend

Is there anything equvilent to this code

plt.plot([1,2,3],[1,2,3],label='22')
z  = plt.legend()
tm = z.get_lines()
tm[0].get_color()

but for errorbars?

plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5],label='22')
z  = plt.legend()
tm = z.get_ ???? 
tm[0].get_color()

I did z.get+ This is what I see: 在此处输入图片说明

I tried many of them but no luck

Thank You.

EDIT: Added proper solution thanks to people from the mailing list.

Workaround way

My best solution so far has been something like this:

plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5])
plt.gca().set_prop_cycle(None) # Reset the color cycle to get the same one
plt.plot([1,2,3],[1,2,3],label='22')
z = plt.legend()
tm = z.get_lines()
tm[0].get_color()

That is plotting the data again. Of course you don't get the same markers in the legend; in my case this wasn't an issue (I'm replacing them by coloring the labels) but YMMV.

Proper way

Scott Lasley hinted that the way to do this is to manipulate plt.legend().legendHandles as pointed by Tom Caswell in answer to OP. They are two subtleties though, the first one is that we are handling LineCollection and not Line2D as noted by Paul Hobson (so that we get arrays in returns), the second is that colors are returned as RGBA arrays instead of HEX values, which might be of importance depending on your use case. So, to get the exact same outputs as in the plt.plot() case with plt.errorbar() , you need to do as follow:

import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5])
z = plt.legend()
tm = z.legendHandles
to_hex(tm[0].get_colors()[0]) # tm[0].get_colors() looks like [[r g b a]]

If you don't care about the color format, you can remove to_hex import and use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM