Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot Splines with ggplot2?

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.

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.

like image 907
Sam Avatar asked Jan 26 '26 06:01

Sam


1 Answers

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

spline() returns a list object of two components, x and 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")
like image 89
Chase Avatar answered Jan 28 '26 19:01

Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!