How do I plot a npdensity
object with ggplot, like one from the output of npudens
?
Use geom_line
together with the built-in functionality of predict
with npdensity
.
df <- data.frame(x = rnorm(1000))
df.kde <- npudens(~x, data=df)
ggplot(df, aes(x))
+ stat_function(fun = function(new.x) predict(df.kde, newdata=data.frame(x=new.x)))
If you have evaluated at enough x points such that the graph looks good, you can get away with using eval$x
and dens
.
geom_line(aes(df.kde$eval$x, df.kde$dens))