Home > Enterprise >  How to define (and plot) a non-continuous function in R?
How to define (and plot) a non-continuous function in R?

Time:12-29

Suppose we have the function y = x^2, we could plot this continuous function from x=0 to x=100 like so:

library("ggplot2")
eq = function(x){x^2}
ggplot(data.frame(x=c(1, 100)), aes(x=x))   
  stat_function(fun=eq)  
  theme_void()

ggplot2 plot of a continuous function

Question

But suppose we wish to define a non continuous function, such that, say, it's the same as y=x^2 but there are no values for x between 20 and 30, and 50 and 70. How could we define it?

Context

I'm trying to replace the second line below (eq = function(x){x*x}) with whatever is necessary in order to plot noncontinuous function (i.e. keeping all other code the same).

library("ggplot2")
eq = function(x){x*x} # CHANGE ONLY THIS LINE (IF POSSIBLE)
ggplot(data.frame(x=c(1, 100)), aes(x=x))   
  stat_function(fun=eq)  
  theme_void()

I'll be trying to plot many non continuous functions on the same plot, so I suspect any hacks on the plot itself (e.g. adding elements over the top of the continuous function) would not scale well..

CodePudding user response:

You can just replace the output of your function with NAs for values of x that aren't part of your domain.

library(ggplot2)

eq <- function(x) {
  ans <- x * x
  ans[x >= 20 & x <= 30] <- NA
  ans[x >= 50 & x <= 70] <- NA
  ans
}

ggplot(data.frame(x = c(1, 100)), aes(x))  
  stat_function(fun = eq)  
  theme_void()

Created on 2021-12-29 by the reprex package (v2.0.1)

  • Related