python添加图例
时间: 2023-07-04 18:27:32 浏览: 51
在 Python 中,我们可以使用 matplotlib 库添加图例。以下是一个简单的示例,演示如何添加图例:
```python
import matplotlib.pyplot as plt
# 创建图形和子图
fig, ax = plt.subplots()
# 绘制数据
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
ax.plot(x, y, label='线条1')
# 添加图例
ax.legend()
# 显示图形
plt.show()
```
在这个例子中,我们首先创建了一个图形和一个子图,然后使用 `ax.plot()` 绘制了一条曲线,并使用 `label` 参数指定了该曲线的标签。最后,我们使用 `ax.legend()` 添加图例。
如果需要添加多个曲线的图例,只需要在每个 `ax.plot()` 调用中使用不同的标签,并在最后一步调用 `ax.legend()`。
请注意,图例的位置可以通过传递 `loc` 参数来调整。例如,`ax.legend(loc='upper right')` 将图例放置在右上角。
相关问题
python添加图例代码
在Python中,使用Matplotlib库可以很方便地添加图例。以下是一个示例代码,展示了如何在不同类型的图中添加图例:
```python
import numpy as np
import matplotlib.pyplot as plt
# Example 1: Line plot
x = np.linspace(0, 2, 100)
plt.figure()
plt.plot(x, x+2, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Legend Example 1")
plt.legend()
# Example 2: Subplot
x = np.linspace(0.0, 5.0)
y = x*x
plt.subplot(2, 1, 2)
plt.plot(x, y, 'g.-',label='quadratic')
plt.plot(x,x, 'r.-', label='linear')
plt.title('Legend Example 2')
plt.xlabel('numbers')
plt.ylabel('Square')
plt.legend()
# Example 3: Bar graph
plt.figure()
plt.barh(np.arange(26), np.random.randint(0,50,26), alpha = 0.5, color='r', label='Legend Bar Graph')
plt.title('Horizontal Bar Graph : Random')
plt.legend()
plt.show()
```
在这个示例代码中,我们使用了`plt.legend()`函数来添加图例。在每个示例中,我们都为不同的数据系列添加了标签,并使用`label`参数来指定它们。然后,我们使用`plt.legend()`函数来自动创建图例。在第一个示例中,我们没有指定位置参数,因此Matplotlib会自动选择最佳位置来放置图例。在第二个和第三个示例中,我们使用了默认的位置参数,将图例放置在右上角。
python matplotlib添加图例
为了在Python的Matplotlib中添加图例,你可以使用plt.legend()函数。该函数可以接受不同的参数来自定义图例的位置、标签和样式。下面是一个示例代码:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')
plt.legend(loc='upper right')
plt.show()
在这个例子中,我们使用了两个线条来绘制y = x^2和y = x^3的曲线,并使用label参数来设置每个线条的标签。然后,我们使用plt.legend()函数将图例添加到图表中,并通过设置loc参数来指定图例的位置。在这个例子中,我们将图例放在右上角。