Matplotlib legend位置设置
在matplotlib中,legend是用来标识不同数据系列的标签。我们可以通过调整legend的位置来使图表更加清晰易懂。下面将介绍如何在matplotlib中设置legend的位置。
默认位置
首先,让我们看一下legend的默认位置。通常,legend会自动放在图表的右上角,不会遮挡数据点。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sin Function')
plt.plot(x, y2, label='Cos Function')
plt.legend()
plt.show()
Output:
设置位置
如果我们希望将legend放置在其他位置,可以使用loc
参数来指定。常用的参数包括:
- ‘upper right’ 或 1
- ‘upper left’ 或 2
- ‘lower left’ 或 3
- ‘lower right’ 或 4
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sin Function')
plt.plot(x, y2, label='Cos Function')
plt.legend(loc='upper left') # 将legend放在左上角
plt.show()
Output:
自定义位置
除了使用预设的位置外,我们还可以通过指定坐标的方式来自定义legend的位置。我们需要使用bbox_to_anchor
参数来指定legend的位置。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sin Function')
plt.plot(x, y2, label='Cos Function')
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1))
plt.show()
Output:
其他位置参数
除了loc
和bbox_to_anchor
外,还有其他一些参数可以用来调整legend的位置。如ncol
参数可以指定列数,borderaxespad
参数可以调整legend和图表的距离等等。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sin Function')
plt.plot(x, y2, label='Cos Function')
plt.legend(loc='upper left', bbox_to_anchor=(0.5, 0.5), ncol=2, borderaxespad=2)
plt.show()
Output:
隐藏legend
有时候我们希望不显示legend,可以将legend()
函数中的show
参数设置为False来隐藏legend。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sin Function')
plt.plot(x, y2, label='Cos Function')
plt.legend(show=False)
plt.show()
通过以上示例代码,我们可以看到如何在matplotlib中设置legend的位置。这将有助于我们更好地展示数据图表,使它更加易于理解。