Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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..

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading