如何用ggplot2绘制样条线?

问题描述

| 我有一些要制作直方图的数据。但是,我想用线表示该直方图。我尝试使用
ggplot2
freq_poly
。但是,生成的行参差不齐。我想知道是否可以将
splines
ggplot2
一起使用,以便使
freq_poly
中产生的线条更平滑。
d <- rnorm( 1000 )
h <- hist( d,breaks=\"FD\",plot=F )
plot( spline( h$mids,h$counts ),type=\"l\" )
这就是我想要完成的。但是我想用
ggplot2
来做。     

解决方法

我假设您正在尝试使用
spline()
函数。如果不是,请忽略此答案。
spline()
返回一个包含两个成分x和y的列表对象:
List of 2
 $ x: num [1:93] -3.3 -3.23 -3.17 -3.1 -3.04 ...
 $ y: num [1:93] 1 0.1421 -0.1642 -0.0228 0.4294 ...
我们可以简单地将它们转换为data.frame并将其绘制出来。可能会有更奇妙的方法来做到这一点,但这将起作用:
h <- hist( d,breaks=\"FD\",plot=F )
zz <- spline( h$mids,h$counts )
qplot(x,y,data = data.frame(x = zz$x,y = zz$y),geom = \"line\")