ggplot2中没有扭结的“分段”函数图

问题描述 投票:0回答:1

我正在尝试复制下面的图表:enter image description here

我的代码如下:

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)

代码有效,但我希望第一个函数仅用于x <= 1的值,而另外两个函数仅用于x > 1的值。我试着玩xlim但到目前为止没有任何效果。另外,我不想在x = 1上扭结,但我真的很困惑如何添加平滑粘贴条件。

初学者在这里,非常感谢一个简单的解决方案!

r ggplot2 smoothing piecewise
1个回答
1
投票

看到这个解决方案

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

© www.soinside.com 2019 - 2024. All rights reserved.