plt.plot显示标签
时间: 2023-10-13 22:00:30 浏览: 207
要在 `plt.plot()` 中显示标签,您可以使用 `plt.legend()` 函数来添加图例。以下是一个示例:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 15, 7, 12, 9]
y2 = [8, 11, 9, 14, 6]
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend()
plt.show()
```
在这个示例中,我们使用 `plt.plot()` 分别绘制了两条线,并使用 `label` 参数为每条线添加了标签。然后,我们使用 `plt.legend()` 函数来显示图例。运行这段代码后,您应该能够看到图例显示在图形中,指示出每条线对应的标签。
您还可以利用 `loc` 参数来控制图例的位置。例如,`plt.legend(loc='upper right')` 可以将图例放置在右上角。可供选择的位置参数有:`upper right`、`upper left`、`lower right`、`lower left` 等等。
注意:在调用 `plt.legend()` 之前,确保已经使用 `plt.plot()` 或其他绘图函数创建了需要添加图例的图形。
相关问题
plt.plot显示数据标签
要在 plt.plot() 中显示数据标签,可以使用 plt.text() 函数。该函数可以在指定的坐标位置添加文本标签。具体步骤如下:
1.在 plt.plot() 中添加参数 label,用于指定数据标签的名称。
2.使用 plt.legend() 函数显示标签。
3.使用 plt.text() 函数在指定的坐标位置添加文本标签。
以下是一个例子:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# 绘制图形
plt.plot(x, y, label='sin(x)') # 添加标签
plt.legend() # 显示标签
# 添加文本标签
plt.text(2, 0, 'Maximum') # 在坐标 (2, 0) 处添加文本标签 Maximum
# 显示图形
plt.show()
```
运行上述代码后,将显示一个正弦曲线,并在坐标 (2, 0) 处添加了文本标签 Maximum。
plt.plot 显示中文
如果想在 `plt.plot` 中显示中文,可以使用以下步骤:
1. 安装中文字体库
```python
!apt-get install -y fonts-wqy-zenhei
```
2. 导入字体库并设置字体
```python
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei'] # 设置中文字体为文泉驿正黑
plt.rcParams['axes.unicode_minus'] = False # 解决负号无法正常显示的问题
```
3. 绘制图形并添加中文标签
```python
import numpy as np
x = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('正弦函数')
plt.xlabel('自变量')
plt.ylabel('因变量')
plt.show()
```
这样就可以在 `plt.plot` 中显示中文了。
阅读全文
相关推荐
















