How do I smooth the edges in line plot? I can do I line plot like this:
data <- data.frame(x=1:10, y=c(22,23,21,25,23,24,20,27,22,24))
ggplot(data, aes(x,y)) +
geom_line(colour='forestgreen')
However, I don't like sharp edges. Is there a way to draw a line through those points so that the line is smooth?
This is one way to do it:
library(ggplot2)
library(splines)
library(gridExtra)
dat <- data.frame(x=1:10, y=c(22,23,21,25,23,24,20,27,22,24))
plot.new() # have to do this unfortunately
res <- xspline(dat$x, dat$y, -0.25, draw=FALSE)
gg1 <- ggplot(dat, aes(x,y)) +
geom_line(colour='forestgreen') +
geom_point()
gg2 <- ggplot(data=data.frame(x=res$x, y=res$y), aes(x, y)) +
geom_point(data=dat, aes(x, y), size=1) +
geom_line(color="blue")
grid.arrange(gg1, gg2, ncol=1)
This is using xspline
to do the interpolation. Lookup the function to see what tweaking the -0.25
parameter (range is -1
to 1
) will do.