如何在功能不连续的地方掉线 [英] How to drop connecting lines where the function is discontinuous
问题描述
我正在绘制一些具有多个不连续性的函数.每个函数都以列表的形式给出.我只想在函数连续的地方用线连接点.
I'm plotting some functions that have several discontinuities. Each function is given as a list. I want to connect points with lines only where the function is continuous.
这是一个关于情节正在做什么的简化示例.
Here is a simplified example of what plot is doing.
x=linspace(0,1,100)
y=zeros(100)
y[x<0.5] = x[x<0.5]
y[x>=0.5] = 1 + x[x>=0.5]
plot(x, y, '-o')
在x = 0.5处有一个不连续点,但是无论如何,plot将所有点都用线连接起来.
There is a discontinuity at x=0.5, but plot connects all points with lines regardless.
我的功能当然不同.它们通常在不同的地方有几个不连续点.不连续性的标准很简单.说,如果函数跳转超过0.5,则我认为该函数在该点是不连续的.
My functions are different of course. They typically have several discontinuities in different places. The criterion for the discontinuity is simple. Say, if the function jumps by more than 0.5, I assume it is discontinuous at that point.
图中是否有选项告诉它在函数不连续的点之间放置连接线?我记得可以使用gnuplot轻松做到这一点.
Is there an option in plot to tell it to drop the connecting lines between the points where the function is discontinuous? I recall being able to do that easily with gnuplot.
推荐答案
使用 nan 将一行分成多段:
use nan to break the line into multiple segments:
import numpy as np
from pylab import *
x=linspace(0,1,100)
y=zeros(100)
y[x<0.5] = x[x<0.5]
y[x>=0.5] = 1 + x[x>=0.5]
pos = np.where(np.abs(np.diff(y)) >= 0.5)[0]
x[pos] = np.nan
y[pos] = np.nan
plot(x, y, '-o')
在不连续处插入nan:
to insert nan at discontinuities:
pos = np.where(np.abs(np.diff(y)) >= 0.5)[0]+1
x = np.insert(x, pos, np.nan)
y = np.insert(y, pos, np.nan)
这篇关于如何在功能不连续的地方掉线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!