Matplotlib Legend for Scatter with custom colours


Question

I'm a bit of newbie at this and am trying to create a scatter chart with custom bubble sizes and colours. The chart displays fine but how do I get a legend saying what the colours refer to. This is as far as I've got:

inc = []
out = []
bal = []
col = []

fig=Figure()
ax=fig.add_subplot(111)

inc = (30000,20000,70000)
out = (80000,30000,40000)
bal = (12000,10000,6000)
col = (1,2,3)
leg = ('proj1','proj2','proj3')

ax.scatter(inc, out, s=bal, c=col)
ax.axis([0, 100000, 0, 100000])

ax.set_xlabel('income', fontsize=20)
ax.set_ylabel('Expenditure', fontsize=20)
ax.set_title('Project FInancial Positions %s' % dt)
ax.grid(True)
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)

This thread was helpful, but couldn't get it to solve my problem: Matplotlib: Legend not displayed properly

1
10
5/23/2017 12:30:26 PM

Accepted Answer

Maybe this example is helpful.

In general, the items in the legend are related with some kind of plotted object. The scatter function/method treats all circles as a single object, see:

print type(ax.scatter(...))

Thus the solution is to create multiple objects. Hence, calling scatter multiple times.

Unfortunately, newer version of matplotlib seem not to use a rectangle in the legend. Thus the legend will contain very large circles, since you increased the size of your scatter plot objects.

The legend function as a markerscale keyword argument to control the size of legend markers, but it seems to be broken.

Update:

The Legend guide recommends using Proxy Artist in similar cases. The Color API explains valid fc values.

p1 = Rectangle((0, 0), 1, 1, fc="b")
p2 = Rectangle((0, 0), 1, 1, fc="g")
p3 = Rectangle((0, 0), 1, 1, fc="r")
legend((p1, p2, p3), ('proj1','proj2','proj3'))

To get the colors used previously in a plot, use the above example like:

pl1, = plot(x1, y1, '.', alpha=0.1, label='plot1')
pl2, = plot(x2, y2, '.', alpha=0.1, label='plot2')
p1 = Rectangle((0, 0), 1, 1, fc=pl1.get_color())
p2 = Rectangle((0, 0), 1, 1, fc=pl2.get_color())
legend((p1, p2), (pl1.get_label(), pl2.get_label()), loc='best')

This example will make a plot like:

Matplotlib with custom legend

9
12/21/2012 3:00:59 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon