如何在 Matplotlib 的散点图中添加图例?
在本文中,我们将使用matplotlib模块为描绘的图像添加图例。我们将使用matplotlib.pyplot.legend()方法来描述和标记图形的元素,并从同一图形中区分不同的图。
Syntax: matplotlib.pyplot.legend( [“title_1”, “Title_2”], ncol = 1 , loc = “upper left” ,bbox_to_anchor =(1, 1) )
Parameters :
- ncol: [takes int, optional parameter] the default value is 1. It represents the number of columns in legend.
- loc: [takes string, optional parameter] the default value is “best” i.e “upper left”. It represents the location of the legend. Other options can be: “best”, “upper right”, “upper left”, “lower left”, “lower right” , “right”, “center left”, “center right”, “lower center”, “upper center”, “center”.
- bbox_to_anchor: [takes a list or tuple of 2 int/float, optional parameter ]. It represents the co-ordinates of legend on the graph. Both x and y co-ordinates are mandatory to give.
示例 1:
Python3
# import required modules
import matplotlib.pyplot as plt
# adjust coordinates
x = [1,2,3,4,5]
y1 = [2,4,6,8,10]
y2 = [3,6,9,12,15]
# depict illustration
plt.scatter(x, y1)
plt.scatter(x,y2)
# apply legend()
plt.legend(["x*2" , "x*3"])
plt.show()
Python3
# impoert required modules
import matplotlib.pyplot as plt
# adjust coordinates
x = [1,2,3,4,5]
y1 = [2,4,6,8,10]
y2 = [3,6,9,12,15]
# depict illustration
plt.scatter(x, y1)
plt.scatter(x,y2)
# appply legend()
plt.legend(["x*2" , "x*3"], ncol = 2 , loc = "lower right")
plt.show()
Python3
# import required modules
import matplotlib.pyplot as plt
# adjust coordinates
x = [1,2,3,4,5]
y1 = [2,4,6,8,10]
y2 = [3,6,9,12,15]
# depict illustartion
plt.scatter(x, y1)
plt.scatter(x,y2)
# apply legend()
plt.legend(["x*2" , "x*3"], bbox_to_anchor = (1 , 1))
plt.show()
Python3
# import required modules
import matplotlib.pyplot as plt
import numpy as np
# assign coordinates
x = np.arange(1, 6)
y1 = x**2
y2 = x**4
# depict illustration
plt.scatter(x, y1, label="x**2")
plt.scatter(x, y2, label="x**4")
# apply legend()
plt.legend()
plt.show()
输出:
示例 2:
蟒蛇3
# impoert required modules
import matplotlib.pyplot as plt
# adjust coordinates
x = [1,2,3,4,5]
y1 = [2,4,6,8,10]
y2 = [3,6,9,12,15]
# depict illustration
plt.scatter(x, y1)
plt.scatter(x,y2)
# appply legend()
plt.legend(["x*2" , "x*3"], ncol = 2 , loc = "lower right")
plt.show()
输出:
示例 3:
蟒蛇3
# import required modules
import matplotlib.pyplot as plt
# adjust coordinates
x = [1,2,3,4,5]
y1 = [2,4,6,8,10]
y2 = [3,6,9,12,15]
# depict illustartion
plt.scatter(x, y1)
plt.scatter(x,y2)
# apply legend()
plt.legend(["x*2" , "x*3"], bbox_to_anchor = (1 , 1))
plt.show()
输出:
注意:我们可以使用“label”参数在 matplotlib.pyplot.scatter() 中标记绘图的元素。但是,要显示它,必须编写matplotlib.pyplot.legend() 。
示例 4:
蟒蛇3
# import required modules
import matplotlib.pyplot as plt
import numpy as np
# assign coordinates
x = np.arange(1, 6)
y1 = x**2
y2 = x**4
# depict illustration
plt.scatter(x, y1, label="x**2")
plt.scatter(x, y2, label="x**4")
# apply legend()
plt.legend()
plt.show()
输出:
注意:如果matplotlib.pyplot.legend()不是用代码编写的,那么标签将不会显示。