matplotlib绘制设置折线图图例
时间: 2023-09-04 20:12:47 浏览: 114
要在 matplotlib 中绘制一个带有图例的折线图,可以按照以下步骤进行操作:
1. 导入 matplotlib 和 numpy 模块:
```python
import matplotlib.pyplot as plt
import numpy as np
```
2. 创建一个数据集,包含 x 坐标和 y 坐标:
```python
x = np.arange(0, 10, 0.1)
y = np.sin(x)
```
3. 绘制折线图:
```python
plt.plot(x, y, label='sin(x)')
```
4. 添加图例:
```python
plt.legend()
```
在这个例子中,我们使用 `label` 参数为折线图指定了一个标签,然后使用 `legend` 函数添加了一个图例。如果在 `legend` 函数中没有指定参数,它会自动使用 `plot` 函数中指定的标签。
完整代码示例:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y, label='sin(x)')
plt.legend()
plt.show()
```
相关问题
matplotlib绘制双轴折线图后如何显示图例
要显示matplotlib绘制的双轴折线图的图例,可以使用plt.legend()函数。该函数可以接受一个包含每个线条标签的列表作为参数,并将其绘制在图表上方。下面是一个简单的双轴折线图例子,展示如何使用plt.legend()函数来显示图例:
```
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 绘制双轴折线图
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-', label='sin')
ax2.plot(x, y2, 'b-', label='cos')
# 显示图例
lines = ax1.get_lines() + ax2.get_lines()
labels = [line.get_label() for line in lines]
plt.legend(lines, labels, loc='best')
plt.show()
```
在上面的例子中,我们首先生成了两个数据集y1和y2,然后使用ax1.plot()和ax2.plot()函数将它们分别绘制在左轴和右轴上。接着,我们使用ax1.get_lines()和ax2.get_lines()函数获取所有的线条对象,并将它们传递给plt.legend()函数,同时将每个线条的标签传递给labels参数。最后,我们使用loc='best'来指定图例的位置,使其尽可能地不遮挡数据。
matplotlib 绘制华丽折线图
以下是一个例子,展示如何使用 matplotlib 绘制华丽折线图:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 设置样式
plt.style.use('seaborn')
# 创建画布和子图
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x, y, color='blue', linewidth=2, linestyle='--', label='sin(x)')
# 添加标题和标签
ax.set_title('Sin(x) Curve')
ax.set_xlabel('x')
ax.set_ylabel('y')
# 设置网格线
ax.grid(True)
# 添加图例
ax.legend()
# 显示图形
plt.show()
```
这个例子中,我们使用 `np.linspace()` 生成了一组 x 值,然后使用 `np.sin()` 计算了相应的 y 值。接着,我们使用 `plt.style.use()` 设置了样式。在这个例子中,我们选择了 seaborn 风格。然后,我们创建了画布和子图,并使用 `ax.plot()` 绘制了折线图。我们设置了线条颜色、线宽、线型和标签。接着,我们添加了标题和标签,设置了网格线,并添加了图例。最后,我们使用 `plt.show()` 显示了图形。
阅读全文
相关推荐
















