4

When I use matplotlib to draw some figures, the legends are always outside the plot. How to keep the legends inside plot ? You can see the result here

I have tried that bbox_to_anchor can work. But it's not convenient due to I don't want to modify the positions every time drawing a new figure.

The code is just an example to reproduce my problem.

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()

I want to keep the all legends inside the plot.

Thanks for any help !

HW_Tang
  • 97
  • 2
  • 9

1 Answers1

3

You can add extra padding between the axes and the legend by adding the "borderaxespad" kwarg to your legend call:

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, borderaxespad=3)
plt.show()

This adds extra space between the legend and the figure boundary so when it is in the lower right corner it will move up and to the left. If it is in the lower left corner it will move up and to the right.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Marc
  • 1,539
  • 8
  • 14