如何在Python中使用Matplotlib绘制步进函数?

rhm*_*012 27 python plot matplotlib

这应该很简单,但我刚开始使用matplotlib和python.我可以做一个直线或散点图,但我不知道如何做一个简单的步骤函数.任何帮助深表感谢.

x = 1,2,3,4
y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 50

好像你想要的step.

例如

import matplotlib.pyplot as plt

x = [1,2,3,4] 
y = [0.002871972681775004, 0.00514787917410944, 
     0.00863476098280219, 0.012003316194034325]

plt.step(x, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 要回答上面的评论,我发现你可以在步骤函数中添加where ='post'参数.所以在上面的例子中,它将是:`plt.step(x,y,where ='post')` (12认同)
  • 好吧,如果你不想要任何垂直线,请看看`plt.hlines`.例如`plt.hlines(y,range(1,5),range(2,6))` (3认同)
  • @Joe Kington:对于一年后的评论感到抱歉.我有点困惑.图表不应该在1到2之间显示0.0028,然后在2时跳转到0.051,依此类推?看起来步骤使用下一个值.(我正在考虑一个时间序列步骤,其中值为t0,并且当它变为b时保持为t1,依此类推.)有没有办法让step()以这种方式运行. (2认同)

Wil*_*den 15

如果您有非均匀间隔的数据点,则可以使用drawstyle关键字参数plot:

x = [1,2.5,3.5,4] 
y = [0.002871972681775004, 0.00514787917410944, 
     0.00863476098280219, 0.012003316194034325]

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

也有steps-midsteps-post.


tdy*_*tdy 6

matplotlib 3.4.0 中的新增功能

有一个新plt.stairs方法可以补充plt.step

plt.stairs底层提供了一个更清晰的界面,用于为您知道步进边缘的StepPatch常见情况绘制步进常数函数。

这取代了 的许多用例plt.step,例如绘制 的输出时np.histogram

查看官方 matplotlib 库以了解如何使用plt.stairsStepPatch


何时使用plt.stepvsplt.stairs

plt.step 与 plt.stairs


plt.stairs与使用np.histogram

由于np.histogram返回边,它可以直接与 一起使用plt.stairs

data = np.random.normal(5, 3, 3000)
bins = np.linspace(0, 10, 20)
hist, edges = np.histogram(data, bins)

plt.stairs(hist, edges)
Run Code Online (Sandbox Code Playgroud)

plt.stairs 与 np.histogram