我使用来自splinefun的值生成了一个ggplot,但是在0附近的区域内值不应该为负,如下图所示.
我想知道当它们为负数时如何强制splinefun中的值为0?谢谢!
sigma <- c(0,1,2,3,4,5,6,7,8,9,10,11,12)
sigma <- matrix(sigma,ncol=1)
myFunc_sig <- function(sigma){
exp(-2/sigma^2)
}
output_sigma <- apply(sigma, 1, myFunc_sig)
spl_fun <- splinefun(sigma, output_sigma)
ggplot(data.frame(x = sigma, y = output_sigma), aes(x, y))+
stat_function(fun = spl_fun, color = "orange")+
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
Run Code Online (Sandbox Code Playgroud)

您可以通过指定method="monoH.FC"或method="hyman"在中要求样条函数是单调的splinefun.例如:
library(tidyverse)
myFunc_sig <- function(sigma){
exp(-2/sigma^2)
}
sigma = 0:12
output_sigma <- myFunc_sig(sigma)
spl_fun <- splinefun(sigma, output_sigma, "monoH.FC")
ggplot(data.frame(x=sigma,y=output_sigma),aes(x,y)) +
stat_function(fun = spl_fun, color = "orange") +
geom_point() +
scale_x_continuous(expand = c(0, 0.1)) +
scale_y_continuous(expand = c(0, 0.02)) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
而随着method="hyman"剧情是这样的:
如果由于某种原因,你确实想对这些值进行人工调整,你可以在外面计算它们ggplot并用它们绘制它们geom_line.例如:
x = seq(min(sigma),max(sigma),length=100)
y = spl_fun(x)
# Set negative values to zero
y[y<0] = 0
ggplot() +
geom_line(data=data.frame(x,y), aes(x,y), colour="orange") +
geom_point(data=data.frame(x=sigma, y=output_sigma), aes(x,y)) +
scale_x_continuous(expand = c(0, 0.1)) +
scale_y_continuous(expand = c(0, 0.02)) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)