如何在 Matplotlib 中将图例放置在绘图之外?
在本文中,我们将看到如何在 Matplotlib 中将图例放置在 Plot 之外?让我们讨论一些概念:
- Matplotlib : Matplotlib 是一个了不起的Python可视化库,用于二维数组绘图。 Matplotlib 是一个基于 NumPy 数组的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起使用。它是由 John Hunter 在 2002 年推出的。
- 图例:图例是描述图形元素的区域。在 matplotlib 库中,有一个名为 legend() 的函数,用于在轴上放置图例。 Legend() 中的属性 Loc 用于指定图例的位置。 loc 的默认值是 loc=”best”(左上角)。
在这里,首先我们将了解为什么需要在外面放置图例。
Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.linspace(-20, 20, 1000)
# plot the graphs
plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))
# add legends
plt.legend(["Sine","Cosine"])
plt.show()
Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.linspace(-20, 20, 1000)
# plot the graphs
plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))
# add legends and set its box position
plt.legend(["Sine","Cosine"],
bbox_to_anchor = (1.05, 0.6))
plt.show()
Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.linspace(-20, 20, 1000)
# plot the graphs
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
# add legends and set its box position
plt.legend(["Sine", "Cosine"],
bbox_to_anchor=(0.6, 1.2))
plt.show()
Python3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x = np.linspace(-5, 5, 1000)
colors=[['c','g'], ['y','r']]
# make subplot and plots the grpahs
fig, ax = plt.subplots(2, 2)
for i in range(2):
ax[0][i].plot(x, np.sin(x+i),
color = colors[0][i],
label = "y=sin(x+{})".format(i))
ax[1][i].plot(x, np.sin(x+i),
color = colors[1][i],
label = "y=sin(x+{})".format(i))
# set legend position
fig.legend(bbox_to_anchor=(1.3, 0.6))
# set spacing to subplots
fig.tight_layout()
plt.show()
输出:
因为,我们可以看到上面的图例在图 ie 上重叠;信息不完整。为了解决这个问题,我们需要将图例放在情节之外。
需要的步骤
- 导入库
- 创建/加载数据
- 制作情节
- 在情节外添加图例。
示例 1:(右侧)
蟒蛇3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.linspace(-20, 20, 1000)
# plot the graphs
plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))
# add legends and set its box position
plt.legend(["Sine","Cosine"],
bbox_to_anchor = (1.05, 0.6))
plt.show()
输出:
示例 2:(顶部)
蟒蛇3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.linspace(-20, 20, 1000)
# plot the graphs
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
# add legends and set its box position
plt.legend(["Sine", "Cosine"],
bbox_to_anchor=(0.6, 1.2))
plt.show()
输出 :
示例 3:(带有子图)
蟒蛇3
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x = np.linspace(-5, 5, 1000)
colors=[['c','g'], ['y','r']]
# make subplot and plots the grpahs
fig, ax = plt.subplots(2, 2)
for i in range(2):
ax[0][i].plot(x, np.sin(x+i),
color = colors[0][i],
label = "y=sin(x+{})".format(i))
ax[1][i].plot(x, np.sin(x+i),
color = colors[1][i],
label = "y=sin(x+{})".format(i))
# set legend position
fig.legend(bbox_to_anchor=(1.3, 0.6))
# set spacing to subplots
fig.tight_layout()
plt.show()
输出 :