Home > Software engineering >  How to combine two function plots in R?
How to combine two function plots in R?

Time:04-01

I can't seem to find a way to combine two ggplots having different function ranges.

library(ggplot2)
myfun <- function(x) {
 1/(1   exp(-x))}

ggplot( NULL,aes(x))   
  stat_function(data=data.frame(x=c(0, 20)),fun=myfun, geom="line")   
  stat_function(data=data.frame(x=c(10, 20)),fun=1/myfun, geom="line")

enter image description here

EDIT: Had a mistake in the question: 1/myfunc instead of myfunc in the second function data.

CodePudding user response:

I am not sure if this is what you want, but I give your function two different colors based on two ranges. You can use the following code:

library(ggplot2)
myfun <- function(x) {
  1/(1   exp(-x))}

ggplot(NULL)   
  stat_function(data= data.frame(x = c(0, 10)), aes(x, color = "blue"), fun=myfun, xlim = c(0,10))  
  stat_function(data= data.frame(x = c(10, 20)), aes(x, color = "red"), fun=myfun, xlim = c(10,20))  
  scale_color_manual(labels = c("blue", "red"), values = c("blue", "red"))

Output:

enter image description here

As you can see in the plot, the function is plotted within two different ranges.

Answer to edited question

I would suggest to just make a second function like this:

library(ggplot2)
myfun1 <- function(x) {
  1/(1   exp(-x))}

myfun2 <- function(x) {
  1/(1/(1   exp(-x)))}

ggplot( NULL)   
  stat_function(data=data.frame(x=c(0, 20)),fun=myfun1, geom="line")   
  stat_function(data=data.frame(x=c(10, 20)),fun=myfun2, geom="line")

Output:

enter image description here

  • Related