python⽤循环打出阶梯图形,matplotlib阶梯图的实现
(step())
step函数概述
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)
其中:
x:类数组结构,⼀维x轴坐标序列。⼀般假设x轴坐标均匀递增。必备参数。
matplotlib中subploty:类数组结构,⼀维y轴坐标序列。必备参数。
fmt:格式字符串,与plot函数的fmt参数类似。可选参数。官⽅建议只设置颜⾊格式。
data:可索引数据,类似于plot函数。可选参数。
**kwargs:类似于plot函数。
where :设置阶梯所在位置,取值范围为{'pre', 'post', 'mid'},默认值为'pre'。
案例:使⽤step函数和plot函数演⽰不同where参数的效果
通过案例可知,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.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.legend(title='Parameter drawstyle:')
plt.title('plt.plot(drawstyle=...)')
plt.show()
到此这篇关于matplotlib阶梯图的实现(step())的⽂章就介绍到这了,更多相关matplotlib 阶梯图内容请搜索脚本之家以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持脚本之家!