如何强制splinefun值为正值?

时间:2017-12-15 19:54:00

标签: r ggplot2 spline

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

The image is in this link

1 个答案:

答案 0 :(得分:6)

您可以通过在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()

enter image description here

对于method="hyman",情节如下:

enter image description here

如果出于某种原因,您确实希望对值进行人工调整,则可以在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()

enter image description here