Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single legend for multiple axes [duplicate]

I have the following example code:

fig1.suptitle('Test') ax1 = fig1.add_subplot(221) ax1.plot(x,y1,color='b',label='aVal') ax2 = ax1.twinx() ax2.plot(x,y2,color='g',label='bVal') ax2.grid( ls='--', color='black') legend([ax1,ax2], loc=2) 

The subplot has two axes with different scales on the same subplot and I want only one legend for both axes. I tried the above code and it does not work and only produces details from ax2. Any ideas?

like image 248
arun Avatar asked Jan 15 '13 18:01

arun


People also ask

What is Legend () when drawing multiple curves in a figure?

Adding legends to the multiple curvesLegends can be added to describe the different curves in the plot. For this, we call the legend() function after plotting the curves. This funciton adds a legend box with appropriate legends at a desired location inside the plot.

How do I add a legend to all subplots?

Create a figure and a set of subplots, using the subplots() method, considering 3 subplots. Plot the curve on all the subplots(3), with different labels, colors. To place the legend for each curve or subplot adding label. To activate label for each curve, use the legend() method.

What is Bbox_to_anchor?

bbox_to_anchor=[x0, y0] will create a bounding box with lower left corner at position [x0, y0] . The extend of the bounding box is zero - being equivalent to bbox_to_anchor=[x0, y0, 0, 0] . The legend will then be placed 'inside' this box and overlapp it according to the specified loc parameter.


1 Answers

I figured it a solution that works! Is there a better way than this?

fig1.suptitle('Test') ax1 = fig1.add_subplot(221) ax1.plot(x,y1,color='b',label='aVal') ax2 = ax1.twinx() ax2.plot(x,y2,color='g',label='bVal') ax2.grid( ls='--', color='black') h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1+h2, l1+l2, loc=2) 
like image 193
arun Avatar answered Sep 23 '22 21:09

arun