rggplot2parametric-equations

How to draw a parametric curve in ggplot2


I'd like to draw a parametric curve in ggplot2. When drawing just points, where ordering doesn't matter, it works OK:

library(ggplot2)
phi = seq(0, 2*pi, length.out=100)
df1 = data.frame(x=(phi+3)*cos(phi), y=(phi+3)*sin(phi))
ggplot(data=df1, aes(x, y)) + geom_point()

points in a spiral

Unfortunately, ggplot2 implicitly sorts the points, so when I attempt to draw a line instead

ggplot(data=df1, aes(x, y)) + geom_line()

I get

failed spiral

which is not what I want. The points should be connected in the same order as they are present in the dataframe. Is there a way to do it in ggplot2?

(I read the answers in Plot a heart in R, but my question is specifically about ggplot2 and using polar coordinates is not an option).


Solution

  • Try the following:

    library(ggplot2)
    phi = seq(0, 2*pi, length.out=100)
    df1 = data.frame(x=(phi+3)*cos(phi), y=(phi+3)*sin(phi))
    ggplot(data=df1, aes(x, y)) + geom_point() + geom_path()
    

    enter image description here