2017-12-15 16 views
3

스플라인 굴림 값을 사용하여 ggplot을 생성했지만 아래 그림에서와 같이 0에 가까운 값은 음수가 아닙니다.R에서 스플라인 굴림 값이 양수가되도록합니다.

음수 일 때 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

답변

5

당신은 splinefunmethod="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() 

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

+0

이 답변 주셔서 감사합니다, 정말 내 문제를 해결! – Xeluk