views:

928

answers:

2

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: http://stackoverflow.com/questions/872397/matplotlib-legend-not-displayed-properly

A: 

Have a look into this:

http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.legend

Hope that helps. If not just ask for more :)

Casey
That's great for lines but not sure how to apply it to a scatter where each separate point is a different colour?
+5  A: 

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'))

This should work.

wierob
Good solution, even if it doesn't work because of the broken markerscale.
tom10
That example is very helpful. Have to go and do proper work for a while but will come back to it this evening.