Search code examples
rggplot2smoothingpiecewise

Graph of "piecewise" function without kinks in ggplot2


I'm trying to replicate the graph below: enter image description here

My code is the following:

fun1 <- function(x){
  314.32*x^2.413
}

fun2 <- function(x){
  350-0.7136*50/x^(2.413*6)
}


fun3 <- function(x){
  2500-4.37136*500/x^(2.413*4)
}

gg1 <- ggplot(data.frame(x = c(0, 3)), 
              aes(x = x))+
  stat_function(fun = fun1)+
  stat_function(fun = fun2)+
  stat_function(fun = fun3)`

gg2 <- gg1 + ylim(0, 2500)

print(gg2)

The code works but I want the first function only for values of x <= 1, and the other two functions only for values of x > 1. I tried to play with xlim but nothing worked so far. In addition, I don't want kinks at x = 1, but I'm really confused about how to add a smooth-pasting condition.

Beginner here, so a simple solution is greatly appreciated!


Solution

  • See this solution:

    fun1 <- function(x){
      ifelse(x<=1, 314.32*x^2.413, NA)
    }
    
    fun2 <- function(x){
      ifelse(x>1, 350-0.7136*50/x^(2.413*6), NA)
    }
    
    
    fun3 <- function(x){
      ifelse(x>1, 2500-4.37136*500/x^(2.413*4), NA)
    }
    
    library(ggplot2)
    gg1 <- ggplot(data.frame(x = c(0, 3)), 
                  aes(x = x))+
      stat_function(fun = fun1, n=1001)+
      stat_function(fun = fun2, n=1001)+
      stat_function(fun = fun3, n=5001)
    
    gg2 <- gg1 + ylim(0, 2500) 
    
    print(gg2)
    

    enter image description here