Skip to main content
 首页 » 编程设计

python之bbox_to_anchor() 函数的参数

2025年05月04日14lautakyan007

import matplotlib.pyplot as plt 
import numpy as np 
 
x = np.arange(10) 
 
fig = plt.figure() 
ax = plt.subplot(111) 
 
for i in xrange(5): 
    ax.plot(x, i * x, label='$y = %ix$' % i) 
 
ax.legend(bbox_to_anchor=(1.1, 1.05)) 
 
plt.show() 

在上面的代码中,我遇到了将图例置于任意位置的函数 bbox_to_anchor。我无法理解该函数的前两个论点,所有文献都说是归一化轴参数。任何机构都可以解释它们是什么以及如何操纵它们吗?

请您参考如下方法:

它不是一个函数,而是一个关键字参数。

总结:您使用 loc 来指定图例的一个角,并且可以选择使用 bbox_to_anchor 来指定该角的位置。默认情况下,图例的指定角将放置在轴的同一角上。

例如 loc='upper right' 只会将图例的右上角放在轴的右上角:

ax.legend(loc='upper right') 

但是如果您希望图例的右上角位于坐标轴的左中,您可以使用 bbox_to_anchor=(0, 0.5):

ax.legend(loc='upper right', bbox_to_anchor=(0, 0.5))