【发布时间】:2020-01-15 11:29:23
【问题描述】:
当我使用 matplotlib 绘制一些图形时,图例总是在情节之外。如何将传说保留在情节中?可以看到结果here
我试过bbox_to_anchor 可以工作。但不方便,因为我不想每次绘制新图形时都修改位置。
代码只是重现我的问题的示例。
import matplotlib.pyplot as plt
import numpy as np
time_step = np.arange(0, 200.01, 40).tolist()
drag3 = [1, 1, 1, 1, 1, 1]
lift3 = [1.5, 1, 1, 1, 1, 0.2]
second_drag3 = [1.2, 1.2, 1.2, 1.3, 1.2, 0.5]
second_lift3 = [1.2, 1.2, 1.2, 1.3, 1.2, 0.8]
fig, ax1 = plt.subplots()
ax1.plot(time_step, drag3, label="40$C_D1$", color='blue', linestyle='-', linewidth=1.0)
ax1.plot(time_step, second_drag3, label="40$C_D2$", color='darkviolet', linestyle='-', linewidth=1.0)
ax2 = ax1.twinx()
ax2.plot(time_step, lift3, label="40$C_L1$", color='red', linestyle='-', linewidth=1.0)
ax2.plot(time_step, second_lift3, label="40$C_L2$", color='limegreen', linestyle='-', linewidth=1.0)
plt.tight_layout()
fig.legend(loc='lower right', ncol=2)
plt.show()
我想把所有的传说都保留在情节中。
感谢您的帮助!
【问题讨论】:
-
编辑您的代码,以便我们重现您的问题。并删除任何与它无关的行。
-
@S.C.A 是的。但我想为所有数字保留
loc='lower right'。 -
如复制,使用
fig.legend(loc='lower right', ncol=2, bbox_to_anchor=(0,0,1,1), bbox_transform=ax1.transAxes)
标签: python matplotlib legend