脚本专栏 发布日期:2025/10/31 浏览次数:1
step函数用于绘制阶梯图。
根据源码可知,step函数是对plot函数的轻量级封装,很多概念和用法与plot函数非常相似。
def step(self, x, y, *args, where='pre', data=None, **kwargs):
 cbook._check_in_list(('pre', 'post', 'mid'), where=where)
 kwargs['drawstyle'] = 'steps-' + where
 return self.plot(x, y, *args, data=data, **kwargs)
step函数签名:
matplotlib.pyplot.step(x, y, *args, where='pre', data=None, **kwargs)
step函数调用签名:
step(x, y, [fmt], *, data=None, where='pre', **kwargs) step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)
其中:
通过案例可知,step函数可以认为是plot函数绘制阶梯图的一个特例。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(14)
y = np.sin(x / 2)
plt.figure(figsize=(12,5))
plt.subplot(121)
plt.step(x, y + 2, label='pre (default)')
plt.plot(x, y + 2, 'o--', color='grey', alpha=0.3)
plt.step(x, y + 1, where='mid', label='mid')
plt.plot(x, y + 1, 'o--', color='grey', alpha=0.3)
plt.step(x, y, where='post', label='post')
plt.plot(x, y, 'o--', color='grey', alpha=0.3)
plt.grid(axis='x', color='0.95')
plt.legend(title='Parameter where:')
plt.title('plt.step(where=...)')
plt.subplot(122)
plt.plot(x, y + 2, drawstyle='steps', label='steps (=steps-pre)')
plt.plot(x, y + 2, 'o--', color='grey', alpha=0.3)
plt.plot(x, y + 1, drawstyle='steps-mid', label='steps-mid')
plt.plot(x, y + 1, 'o--', color='grey', alpha=0.3)
plt.plot(x, y, drawstyle='steps-post', label='steps-post')
plt.plot(x, y, 'o--', color='grey', alpha=0.3)
plt.grid(axis='x', color='0.95')
plt.legend(title='Parameter drawstyle:')
plt.title('plt.plot(drawstyle=...)')
plt.show()