I have this python code.
- it twinx the axis
ax
and plots some function on both axis - I plot the legend on
ax1
The problem is that the legend is not covering the curves of ax2
It is possible to automatically positioning the legend on ax
by covering the lines of ax2
.
Note that in fig.legend
the option loc="best"
is not available.
And I need the automatic positioning inside the area of the plot.
Tnx
import matplotlib.pyplot as plt
import numpy as np
# Set the x values for the sine and cosine functions
x = np.linspace(0, 2*np.pi, 100)
# Create the figure and an axis
fig, ax = plt.subplots()
ax2 = ax.twinx()
# Plot the sine and cosine functions on the axis
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax2.plot(x, np.cos(x+1), label='Cosine 2', color="red")
ax2.plot(x, x, label='Cosine 2', color="green")
# Add a title and labels to the axis
ax.set_title('Sine and Cosine Functions')
ax.set_xlabel('X')
ax.set_ylabel('Y')
# Get the line legends from the axis
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
# Add a legend to the figure
ax.legend(lines + lines2, labels + labels2, framealpha=1.0)
ax.get_legend().set_zorder(10)
# Display the plot
plt.show()
Bellow is the output of the code:
References:
The
zorder
of alegend
is highest by default, so you don't need to modify it if you want thelegend
on the top of everything.Option 1:
You can accomplish this in terms of a
Figure
object instead of anAxes
object withplt.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')
.Option 2:
Or you can set the legend on
ax2
instead ofax
withax2.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')
. This returns the same result as in option 1.Results (
loc='lower left'
andloc='lower center'
):Updated:
Reference: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.twinx.html
With option 2 in my previous answer, I edited line 36 to
ax2.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower right')
and line 43 toax22.legend(lines1 + lines22, labels1 + labels22, framealpha=1.0, loc='lower left')
in your newly provided code.If you have multiple subfigures, using
Axes
objects are much more flexible.It is now working correctly: