更改 Matplotlib 中的图例位置
在本文中,我们将学习如何在 Matplotlib 中更改图例位置。让我们讨论一些概念:
- Matplotlib 是一个巨大的Python可视化库,用于数组的 2D 绘图。 Matplotlib 可能是一个基于 NumPy 数组的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起计算。它是由约翰亨特在 2002 年引入的。
- 图例是描述图形元素的区域。在 matplotlib 库中,有一个名为 legend() 的函数,用于在轴上放置图例。
- Legend()中的属性Loc用于指定图例的位置。loc的默认值为loc=”best”(左上)。字符串最好右上、左上、左下、右下、右、中左、中右、中下、中上和中心将图例放置在轴/图形的相应角。
Location String | Location String |
Best | 0 |
Upper right | 1 |
Upper left | 2 |
Lower left | 3 |
Lower right | 4 |
Right | 5 |
Center left | 6 |
Center right | 7 |
Lower center | 8 |
Upper center | 9 |
center | 10 |
方法:
- 导入库 (Matplotlib)
- 导入/创建数据。
- 绘制图表。
- 添加图例。
- 使用 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()
输出: