Home > Back-end >  Plot a discontinuous function in R without connecting a "jump"
Plot a discontinuous function in R without connecting a "jump"

Time:09-13

I'd like to plot a discontinuous function without connecting a jump. For example, in the following plot, I'd like to delete the line connecting (0.5, 0.5) and (0.5, 1.5).

f <- function(x){
  (x < .5) * (x)   (x >= .5) * (x   1)
}
ggplot()  
  geom_function(fun = f)

Edit: I'm looking for a solution that works even if the discountinuous point is not a round number, say pi/10.

CodePudding user response:

You could write a little wrapper function which finds discontinuities in the given function and plots them as separate groups:

plot_fun <- function(fun, from = 0, to = 1, by = 0.001) {
  
  x <- seq(from, to, by)
  groups <- cut(x, c(-Inf, x[which(abs(diff(fun(x))) > 0.1)], Inf))
  df <- data.frame(x, groups, y = fun(x))
  
  ggplot(df, aes(x, y, group = groups))  
    geom_line()
}

This allows

plot_fun(f)

enter image description here

plot_fun(floor, 0, 10)

enter image description here

CodePudding user response:

You can insert everything inside an ifelse:

f <- function(x){
  ifelse(x==0.5, 
         NA, 
         (x < .5) * (x)   (x >= .5) * (x   1))
}
ggplot()  
  geom_function(fun = f)

enter image description here

  • Related