Python中的 Matplotlib.pyplot.figlegend()函数
Matplotlib是一个Python库,用于使用 Pyplot 创建、动画和编辑图形、绘图和图形。 Matplotlib.pyplot根据用户需求的偏好和要求,在其中定义了许多要使用的功能。
matplotlib.pyplot.figlegend()函数
这用于在图形上放置图例。 Matplotlib 中的图例类似于图中定义治疗方法的铭牌。
Syntax: matplotlib.pyplot.figlegend(*args, **kwargs)
Parameters: some important parameters are:
- handles: list of all figure lines(or in technical tern Artist) A list of Artists (lines, patches) to be added to the legend is given to be the different handles. Specifying handles is optional in figlend().
- labels: list of actual name of the legends A list of labels to show what is the actual value of the Artist are called labels. Specifying labels is optional in figlend() and if labels are not specified then the figlend() function will name them Legend 1, Legend 2 and so on.
- loc : Location of the legend(default: ‘best’).
Returns: returns the Legend to be put on figure.
示例 1:创建一个数据集 x,其值为 x = [0, 0.1, 0.2,….,5] 和 y = sin(x),然后用数据集 x 在 x 轴和 y 在 y 轴绘制图形label = “Sin” 并使用默认的 figlegend() 绘制图形,并使用之前指定的标签作为图例。
Python3
# Importing the necessary modules
import numpy as np
import matplotlib.pyplot as plt
# Creating a dataset
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Plotting the data
plt.plot(x, y, label = "Sin")
# Legend
plt.figlegend()
Python3
# Importing the necessary modules
import numpy as np
import matplotlib.pyplot as plt
# Creating a dataset
x = np.arange(0, 5, 0.1)
y = np.cos(x)
# Plotting the data
line1 = plt.plot(x, y)
# Legend
plt.figlegend((line1),('Cos'))
Python3
# Importing the necessary modules
import numpy as np
import matplotlib.pyplot as plt
# Creating a dataset
x = np.arange(0, 5, 0.1)
y = np.tan(x)
x1 = np.arange(0, 5, 0.1)
y1 = np.cos(x)
# Plotting the data
line1 = plt.plot(x, y)
line2 = plt.plot(x1, y1)
# Legend
plt.figlegend(
handles = (line1,line2),
labels = ("Tan","Cos"),
loc='upper right')
输出:
示例 2:使用与上述相同的方法,但显示使用 figlegend() 句柄和标签,但使用默认位置。
Python3
# Importing the necessary modules
import numpy as np
import matplotlib.pyplot as plt
# Creating a dataset
x = np.arange(0, 5, 0.1)
y = np.cos(x)
# Plotting the data
line1 = plt.plot(x, y)
# Legend
plt.figlegend((line1),('Cos'))
输出:
示例 3:通过在一张 tan 和 cos函数图上绘制两个图形来展示 figlegend(handles, labels, location)函数的使用。
Python3
# Importing the necessary modules
import numpy as np
import matplotlib.pyplot as plt
# Creating a dataset
x = np.arange(0, 5, 0.1)
y = np.tan(x)
x1 = np.arange(0, 5, 0.1)
y1 = np.cos(x)
# Plotting the data
line1 = plt.plot(x, y)
line2 = plt.plot(x1, y1)
# Legend
plt.figlegend(
handles = (line1,line2),
labels = ("Tan","Cos"),
loc='upper right')
输出: