如何强制 splinefun 值为正?

How to force splinefun values to be positive?

我使用 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))

您可以通过在 splinefun 中指定 method="monoH.FC"method="hyman" 来要求样条函数是单调的。例如:

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()

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()