Matplotlib在步骤图中仅绘制水平线 [英] Matplotlib plot only horizontal lines in step plot

查看:53
本文介绍了Matplotlib在步骤图中仅绘制水平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib从数据框中绘制一些步骤函数

I am using matplotlib to plot some step functions from a dataframe

df['s1'].plot(c='b', drawstyle="steps-post")
df['s2'].plot(c='b', drawstyle="steps-post")
...

结果看起来像

我想只绘制水平线,而不是连接跳跃点的垂直线.我找不到一个简单的情节参数似乎可以做到这一点.有办法吗?

I would like to have this only plot the horizontal lines, not the vertical lines connecting the jump points. I could not find a straightforward parameter for plot that would seem to do that. Is there a way to do this?

推荐答案

据我所知,没有内置选项可以生成没有垂直线的阶梯函数.但是您可以轻松地自己构建一个.以下使用 np.nan 未绘制并切断线的事实.因此,在步骤之间添加 np.nan 会抑制垂直线.

There is no built-in option to produce a step function without vertical lines as far as I can tell. But you may easily build one yourself. The following uses the fact that np.nan is not plotted and cuts the line. So adding np.nan in between the steps suppresses the vertical line.

import matplotlib.pyplot as plt
import numpy as np

def mystep(x,y, ax=None, where='post', **kwargs):
    assert where in ['post', 'pre']
    x = np.array(x)
    y = np.array(y)
    if where=='post': y_slice = y[:-1]
    if where=='pre': y_slice = y[1:]
    X = np.c_[x[:-1],x[1:],x[1:]]
    Y = np.c_[y_slice, y_slice, np.zeros_like(x[:-1])*np.nan]
    if not ax: ax=plt.gca()
    return ax.plot(X.flatten(), Y.flatten(), **kwargs)
    
x = [1,3,4,5,8,10,11]
y = [5,4,2,7,6,4,4]

mystep(x,y, color="crimson")

plt.show()

这篇关于Matplotlib在步骤图中仅绘制水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆