如何用ggplot2绘制样条?

时间:2022-11-23 14:56:01

I have some data that i want to make a histogram of. However, I want to represent this histogram with line. I have tried using the freq_poly of the ggplot2. However, the line produced is pretty jagged. I want to know if it is possible to use the splines with ggplot2, so that the line produced in freq_poly will be smoother.

我有一些数据要做直方图。但是,我想用直线表示这个直方图。我试过使用ggplot2的freq_poly。然而,生产出来的生产线却参差不齐。我想知道是否可以使用带有ggplot2的样条,以便在freq_poly中生成的线更加平滑。

d <- rnorm( 1000 )
h <- hist( d, breaks="FD", plot=F )
plot( spline( h$mids, h$counts ), type="l" )

This is what i want to accomplish. But I want to do it using ggplot2.

这就是我想要实现的。但是我想用ggplot2来做。

1 个解决方案

#1


4  

I'm assuming that you are trying to use the spline() function. If not, disregard this answer.

我假设您正在尝试使用spline()函数。如果不是,就忽略这个答案。

spline() returns a list object of two components, x and y:

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 ...

We can simply turn these into a data.frame and plot them There may be a fancier ways to do this, but this will work:

我们可以简单地把这些数据转换成数据。框架并绘制它们可能有更奇特的方法,但这将会起作用:

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")

#1


4  

I'm assuming that you are trying to use the spline() function. If not, disregard this answer.

我假设您正在尝试使用spline()函数。如果不是,就忽略这个答案。

spline() returns a list object of two components, x and y:

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 ...

We can simply turn these into a data.frame and plot them There may be a fancier ways to do this, but this will work:

我们可以简单地把这些数据转换成数据。框架并绘制它们可能有更奇特的方法,但这将会起作用:

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")