python一张图画多个不同的图例
时间: 2023-04-06 09:02:05 浏览: 65
可以使用 Matplotlib 库中的 subplot() 函数来实现。具体步骤如下:
1. 创建一个画布和多个子图,使用 subplot() 函数指定子图的行数、列数和子图编号。
2. 在每个子图中绘制不同的图形,并使用 legend() 函数添加图例。
3. 最后使用 show() 函数显示图形。
示例代码如下:
import matplotlib.pyplot as plt
# 创建画布和子图
fig, axs = plt.subplots(nrows=2, ncols=2)
# 在子图中绘制图形并添加图例
axs[0, 0].plot([1, 2, 3], [4, 5, 6], label='Line 1')
axs[0, 0].legend()
axs[0, 1].scatter([1, 2, 3], [4, 5, 6], label='Scatter 1')
axs[0, 1].legend()
axs[1, 0].bar([1, 2, 3], [4, 5, 6], label='Bar 1')
axs[1, 0].legend()
axs[1, 1].pie([1, 2, 3], labels=['Pie 1', 'Pie 2', 'Pie 3'])
axs[1, 1].legend()
# 显示图形
plt.show()
相关问题
python一张图画多个图例
可以使用 matplotlib 库中的 legend() 方法来实现一张图画多个图例。具体实现方法可以参考以下代码:
import matplotlib.pyplot as plt
# 画图
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6], label='Line 1')
ax.plot([1, 2, 3], [2, 4, 6], label='Line 2')
ax.plot([1, 2, 3], [1, 3, 5], label='Line 3')
# 添加图例
legend1 = ax.legend(loc='upper left')
legend2 = ax.legend(loc='lower right')
ax.add_artist(legend1)
plt.show()
这样就可以在一张图中画出多个图例了。
python一张图画多个变量
在Python中,可以使用Matplotlib库来绘制图表。如果要在一张图中画多个变量,可以使用subplot函数来实现。
下面是一个简单的例子,展示如何使用subplot函数画多个变量的图表:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
# 绘制图表
fig, axs = plt.subplots(2, 1, figsize=(8, 6))
axs[0].plot(x, y1, label='sin(x)')
axs[0].legend()
axs[1].plot(x, y2, label='cos(x)')
axs[1].legend()
plt.show()
```
这个例子中,我们先生成了两个变量y1和y2,分别表示sin(x)和cos(x)的值。然后使用subplot函数创建了一个2行1列的图表,并将每个变量的图像分别绘制到不同的子图中。最后使用plt.show()函数显示图表。
你可以根据自己的需求修改代码,来实现不同的图表布局和样式。