matplotlib.pyplot柱状图设置标准线
时间: 2023-07-12 18:34:51 浏览: 146
在 Matplotlib 中,我们可以使用 `ax.axhline()` 和 `ax.axvline()` 函数在柱状图上添加水平和垂直的标准线。这里以添加水平标准线为例,步骤如下:
1. 导入 Matplotlib 库:
```
import matplotlib.pyplot as plt
```
2. 准备数据和标准线位置:
```
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
y_std = 25
```
3. 创建一个画布和子图:
```
fig, ax = plt.subplots()
```
4. 使用 `bar` 函数画出柱状图:
```
ax.bar(x, y)
```
5. 添加水平标准线:
```
ax.axhline(y=y_std, color='r', linestyle='--')
```
其中,`y` 参数指定标准线的位置,`color` 参数指定标准线的颜色,`linestyle` 参数指定标准线的样式。
6. 添加标题和轴标签:
```
ax.set_title('Bar Chart with Standard Line')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
```
7. 显示图形:
```
plt.show()
```
完整代码如下:
```
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
y_std = 25
fig, ax = plt.subplots()
ax.bar(x, y)
ax.axhline(y=y_std, color='r', linestyle='--')
ax.set_title('Bar Chart with Standard Line')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
plt.show()
```
你可以根据自己的需求修改标准线的位置、颜色和样式等属性。
阅读全文
相关推荐


















