如何制作只包含垂直线和水平线的Python图表?

Cha*_*iou 7 python matplotlib

如何画这样的东西?有点像一条水平线,直到下一个数据点出现,然后是一条垂直线来调整位置 y。matplotlib中常用的绘图函数只是在两个数据点之间绘制一条直线,这不能满足我的需要。

示例截图

Imp*_*est 8

您可以使用其中一种绘制样式"steps-pre", "steps-mid","steps-post"来获得曲线的阶梯状外观。

plt.plot(x,y, drawstyle="steps-pre")
Run Code Online (Sandbox Code Playgroud)

完整示例:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed()

x = np.arange(12)
y = np.random.rand(12)

styles = ["default","steps-pre","steps-mid", "steps-post"]

fig, axes = plt.subplots(nrows=len(styles), figsize=(4,7))

for ax, style in zip(axes, styles):
    ax.plot(x,y, drawstyle=style)
    ax.set_title("drawstyle={}".format(style))

fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述