Question

I want to produce a line plot for a function with some discontinuities. My function has been formed from a simulated brownian motion path as follows:

  t <- 1:100
  std <- 0.01
  x <- rnorm(n = length(t) - 1, sd = sqrt(std))
  x <- c(0, cumsum(x))

  #add in some discontinuities

  x[25:35] <- x[25:35] + 0.2
  x[45:55] <- x[45:55] - 0.5

My approach has been to set up an empty plot with plot(0, xlim = c(-49,50), ylim = c(-2, 2)) and then try to add the continuous pieces of the function in steps via

  lines((-49):(-25), x[1:25])
  lines((-25):(-15), x[25:35])
  lines((-15):(-5), x[35:45])
  lines((-5):5, x[45:55])
  lines(5:50, x[55:100])

The problem is that the resulting plot is continuous. For some reason R is connecting what should be disjoint pieces of the graph. How can I suppress this behavior?

Thanks very much!

Was it helpful?

Solution

Again, some of your lines commands have errors as your x and y lengths differ (e.g. in lines((-15):5, x[35:45]), -15:5 is 21 elements long whereas x[35:45] is 11 elements long, and a few other of your lines calls too).

However, your problem is that when you are drawing your lines you are including the 'break point' in both lines calls.

First, let's construct some simpler data...

x <- 1:10
y <- c(1:5, 10:15)

Plot the first segment:

plot(x[1:5], y[1:5], xlim=range(x), ylim=range(y), type='l') # type='l' draws a line

Note that the next segment is x[6:10], not x[5:10] as you have been doing.

lines(x[6:10], y[6:10])

And you get:

enter image description here

So basically when you plot your segments, ensure that they are actually distinct from each other (since lines and plot plot inclusive of the end points):

e.g. instead of:

lines((-49):(-25), x[1:25]) lines((-25):(-15), x[25:35])

use

lines((-49):(-25), x[1:25]) lines((-24):(-15), x[26:35]) # <-- remove overlap

and so on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top