📜  如何在 Matplotlib 的散点图中添加图例?

📅  最后修改于: 2022-05-13 01:55:29.700000             🧑  作者: Mango

如何在 Matplotlib 的散点图中添加图例?

在本文中,我们将使用matplotlib模块为描绘的图像添加图例。我们将使用matplotlib.pyplot.legend()方法来描述和标记图形的元素,并从同一图形中区分不同的图。

示例 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()不是用代码编写的,那么标签将不会显示。