📌  相关文章
📜  更改 Matplotlib 中的图例位置

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

更改 Matplotlib 中的图例位置

在本文中,我们将学习如何在 Matplotlib 中更改图例位置。让我们讨论一些概念:

  • Matplotlib 是一个巨大的Python可视化库,用于数组的 2D 绘图。 Matplotlib 可能是一个基于 NumPy 数组的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起计算。它是由约翰亨特在 2002 年引入的。
  • 图例是描述图形元素的区域。在 matplotlib 库中,有一个名为 legend() 的函数,用于在轴上放置图例。
  • Legend()中的属性Loc用于指定图例的位置。loc的默认值为loc=”best”(左上)。字符串最好右上、左上、左下、右下、右、中左、中右、中下、中上和中心将图例放置在轴/图形的相应角。
Location StringLocation String
Best0
Upper right1
Upper left2
Lower left3
Lower right4
Right5
Center left6
Center right7
Lower center8
Upper center9
center10

方法:

  1. 导入库 (Matplotlib)
  2. 导入/创建数据。
  3. 绘制图表。
  4. 添加图例。
  5. 使用 loc 设置图例的位置。

示例 1:

Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend
plt.legend(['Legend'])
plt.show()


Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to upper left
plt.legend(['Legend'], loc='upper left')
plt.show()


Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to lower left i.e; 4
plt.legend(['Legend'], loc=4)
plt.show()


Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to lower right
plt.legend(['Legend'], loc='lower right')
plt.show()


输出:

不设置图例位置(最佳)

示例 2:

蟒蛇3

# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to upper left
plt.legend(['Legend'], loc='upper left')
plt.show()

输出:

左上角的图例

示例 3:

蟒蛇3

# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to lower left i.e; 4
plt.legend(['Legend'], loc=4)
plt.show()

输出:

左下角的图例

示例 4:

蟒蛇3

# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to lower right
plt.legend(['Legend'], loc='lower right')
plt.show()

输出:

右下角的图例