library(ggplot2)
# to plot a rectangle
x = c(0, 1, 1, 0, 0)
y = c(0, 0, 1, 1, 0)
ggplot(NULL, aes(x, y)) geom_line()
CodePudding user response:
The reason that the top line is missing is that geom_line
sorts the co-ordinates according to their position on the x axis before plotting them. It does not plot points in the order in which they appear in the vector.
It is a geom_path
that allows arbitrary ordering of x and y values and would produce the lines you want:
x = c(0, 1, 1, 0, 0)
y = c(0, 0, 1, 1, 0)
ggplot(NULL, aes(x, y)) geom_path()
In a sense, a geom_line
is just a geom_path
where the points have been ordered by ascending x value. We can replicate the behaviour of geom_line
by ordering manually:
ggplot(NULL, aes(x[order(x)], y[order(x)])) geom_path()