Matplotlib legend位置设置

Matplotlib legend位置设置

参考:legend position matplotlib

在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:

Matplotlib legend位置设置

设置位置

如果我们希望将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:

Matplotlib legend位置设置

自定义位置

除了使用预设的位置外,我们还可以通过指定坐标的方式来自定义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:

Matplotlib legend位置设置

其他位置参数

除了locbbox_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:

Matplotlib legend位置设置

隐藏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的位置。这将有助于我们更好地展示数据图表,使它更加易于理解。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程