Python 非重叠图例和轴(例如,在matplotlib中)

Python 非重叠图例和轴(例如,在matplotlib中),python,matplotlib,plot,Python,Matplotlib,Plot,我需要打印图例与打印轴并排显示,即在轴外部,且不重叠 轴和图例的宽度应“自动”调整,以便它们都填充图形,而不重叠或切割图例,即使在使用时也是如此。图例应占据图形的一小部分(假设最大为图形宽度的1/3,以便剩余的2/3专用于实际绘图) 最终,图例条目的字体可以自动减少以满足要求 我在matplotlib中阅读了大量关于legend和bbox\u to\u anchor的答案,其中: 我尝试创建一个专用轴来放置图例,这样plt.tight_layout()就能正常工作,但图例只占用专用轴的一

我需要打印图例与打印轴并排显示,即在轴外部,且不重叠

图例
的宽度应“自动”调整,以便它们都填充图形,而不重叠或切割图例,即使在使用时也是如此。图例应占据图形的一小部分(假设最大为图形宽度的1/3,以便剩余的2/3专用于实际绘图)

最终,图例条目的字体可以自动减少以满足要求

我在matplotlib中阅读了大量关于
legend
bbox\u to\u anchor
的答案,其中:

我尝试创建一个专用轴来放置图例,这样plt.tight_layout()就能正常工作,但图例只占用专用轴的一小部分,结果浪费了大量空间。或者,如果没有足够的空间(图形太小),图例仍然与第一个轴重叠

import matplotlib.pyplot as plt
import numpy as np

# generate some data
x = np.arange(1, 100) 

# create 2 side-by-side axes
fig, ax = plt.subplots(1,2)
# create a plot with a long legend 
for ii in range(20):
    ax[0].plot(x, x**2, label='20201110_120000')
    ax[0].plot(x, x, label='20201104_110000')

# grab handles and labels from the first ax and pass it to the second
hl = ax[0].get_legend_handles_labels() 
leg = ax[1].legend(*hl, ncol=2)
plt.tight_layout()

我愿意使用与matplotlib不同的软件包。

您可以将
loc
传递到
legend
,而不是尝试在单独的轴上绘制图例:

# create 2 side-by-side axes
fig, ax = plt.subplots(figsize=(10,6))
# create a plot with a long legend 
for ii in range(20):
    ax.plot(x, x**2, label='20201110_120000')
    ax.plot(x, x, label='20201104_110000')

# grab handles and labels from the first ax and pass it to the second
ax.legend(ncol=2, loc=[1,0])
plt.tight_layout()
输出:


啊!我用
图形图例
而不是
轴图例
尝试了此选项,但效果不佳。使用
loc=[1,0]
图形图例
将图例置于图形本身之外,因此它是不可见的。使用
轴图例
可按预期工作。