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?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With