Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, matplotlib - legend based on a conditional variable -

I have a data, which can be used in scatter plot.

I also have labels for the same data. So I am using conditional coloring:

# import needed things
fig = plt.figure()
r = fig.add_subplot(121)
r.scatter(np.arange(500), X[ :500, 0] c = Y[:500]
# x and y labels set here

g = fig.add_subplot(122)
g.scatter(np.arange(500), X[ :500, 1] c = Y[:500]
# x and y labels set here

plt.show()    

I need to have a legend as well, suggesting which type has which color. I tried this:

plt.legend((r, g), ("one", "zero"), scatterpoints = 1, loc = "upper left")

but I get a warning

.../site-packages/matplotlib/legend.py:633: UserWarning: Legend does not support <matplotlib.axes._subplots.AxesSubplot object at 0x7fe37f460668> instances.
A proxy artist may be used instead.

and legend is not displayed.

like image 502
Adorn Avatar asked Apr 24 '26 06:04

Adorn


1 Answers

I was able to run your code by substituting

r.scatter(np.arange(500), np.arange(500), c= np.arange(500))
g.scatter(np.arange(500), np.arange(500), c= np.arange(500))

I got a similar error that points me to a page on matplotlib.org, see below:

/Users/sdurant/anaconda/lib/python2.7/site-packages/matplotlib/legend.py:611: UserWarning: Legend does not support instances. A proxy artist may be used instead. See: http://matplotlib.org/users/legend_guide.html#using-proxy-artist "#using-proxy-artist".format(orig_handle))

I don't understand exactly what you want your legend to look like, but that page has examples for a few types, hope this helps.

Edit: That makes more sense, is this roughly what you are looking for then?

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='one')
blue_patch = mpatches.Patch(color='blue', label='zero')

area = np.pi *30
fig = plt.figure()
r = fig.add_subplot(121)
r.scatter(np.arange(10), np.arange(10), c= [random.randint(2) for k in range(10)], s=area)
# x and y labels set here
plt.legend(handles=[red_patch,blue_patch])
g = fig.add_subplot(122)
g.scatter(np.arange(10), np.arange(10), c= [random.randint(2) for k in range(10)], s=area)
# x and y labels set here

plt.legend(handles=[red_patch,blue_patch])

enter image description here

like image 84
steven Avatar answered Apr 26 '26 21:04

steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!