参考:
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
https://matplotlib.org/stable/gallery/misc/zorder_demo.html https://matplotlib.org/stable/gallery/misc/zorder_demo.html
The zorder
of a legend
默认是最高的,所以如果你想要的话,不需要修改它legend
在一切之上。
选项1:
您可以通过以下方式完成此任务Figure
对象而不是Axes
对象与plt.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')
.
选项2:
或者您可以将图例设置为ax2
代替ax
with ax2.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')
。这将返回与选项 1 相同的结果。
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
plt.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')
# Display the plot
plt.show()
结果 (loc='lower left'
and loc='lower center'
):
Updated:
参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.twinx.html https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.twinx.html
对于我之前的答案中的选项 2,我将第 36 行编辑为ax2.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower right')
和第 43 行到ax22.legend(lines1 + lines22, labels1 + labels22, framealpha=1.0, loc='lower left')
在您新提供的代码中。
如果您有多个子图,请使用Axes
对象更加灵活。
现在可以正常工作了: