2017-12-15 5 views
3

Ich habe einen ggplot mit Werten von Splinefun generiert, aber die Werte sollten nicht negativ sein in dem Bereich in der Nähe von 0, wie in der folgenden Abbildung gezeigt.In R, forcing splinefun Werte positiv zu sein

Ich frage mich, wie man die Werte in Splinefun auf 0 setzen, wenn sie negativ sind? Vielen Dank!

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

Antwort

5

Sie können die Spline-Funktion erfordert durch die Angabe method="monoH.FC" oder method="hyman" in splinefun monotone zu sein. Zum Beispiel:

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

Und mit method="hyman" die Handlung sieht wie folgt aus:

enter image description here

Wenn aus irgendeinem Grund, Sie wollten künstliche Anpassungen der Werte machen, Sie könnten sie außerhalb ggplot berechnen und sie mit geom_line plotten. Zum Beispiel:

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

Vielen Dank für Ihre Antwort, löst wirklich mein Problem! – Xeluk