# Matplotlib 中如何将图例放置在绘图之外

Jinku Hu 2023年1月30日 2020年3月28日 Matplotlib Matplotlib Legend

``````plt.legend(bbox_to_anchor=(1.05, 1))
``````

``````plt.legend(bbox_to_anchor=(x0, y0, width, height), loc=)
``````

`width``height` 是图例框的宽度和高度，而 `(x0, y0)` 是边界框 `loc` 的坐标。

loc 的值可以是具有以下关系的数字或字符串，

`loc` 编号 `loc 字符串`
0 `best`
1 `upper right`
2 `upper left`
3 `lower left`
4 `lower right`
5 `right`
6 `center left`
7 `center right`
8 `lower center`
9 `upper center`
10 `center`
``````plt.legend(bbox_to_anchor=(1.05, 1.0, 0.3, 0.2), loc='upper left')
``````

## `bbox_to_anchor` 示例

``````import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")

plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.tight_layout()
plt.show()
``````

`plt.tight_layout()` 使子图合适的跟图形匹配。

## `bbox_extra_artists` 和 `bbox_inches` 以防止图例框被裁剪

``````import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")

lg = plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')

plt.savefig('example.png',
dpi=300,
format='png',
bbox_extra_artists=(lg,),
bbox_inches='tight')
``````

`bbox_extra_artists` 指定 `Artist` 的列表，该列表在计算紧凑 `bbox` 时会考虑在内。

Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.