24

I have a series of ordered points as shown below: enter image description here

However when I try to connect the points by a line, I get the following output: enter image description here

The plot is connecting 26 to 1 and 25 to 9 and 10 (some of the errors), instead of following the order. The code for plotting the points is given below:

p<-ggplot(aes(x = x, y = y), data = spat_loc)
p<-p + labs(x = "x Coords (Km)", y="Y coords (Km)") +ggtitle("Locations")
p<-p + geom_point(aes(color="Red",size=2)) + geom_text(aes(label = X))
p + theme_bw()

Plotting code:

p + 
geom_line((aes(x=x, y=y)),colour="blue") +
theme_bw()

The file which contains the locations have the following structure:

X    x    y
1    210  200 
.
.
.

where X is the numeric ID and x and y are the pair of co-ordinates.

What do I need to do to make the line follow the ordering of points?

user213544
  • 2,046
  • 3
  • 22
  • 52
DotPi
  • 3,977
  • 6
  • 33
  • 53

1 Answers1

42

geom_path() will join points in the original order, so you can order your data in the way you want it joined, and then just do + geom_path(). Here's some dummy data:

dat <- data.frame(x = sample(1:10), y = sample(1:10), order = sample(1:10))
ggplot(dat[order(dat$order),], aes(x, y)) + geom_point() + geom_text(aes(y = y + 0.25,label = order)) +
  geom_path()

enter image description here

alexwhan
  • 15,636
  • 5
  • 52
  • 66
  • Changing the `position` arg within `geom_path` to `=position_dodgev(1)` (vertical position dodge) connects points based on their order on the y axis; `=position_dodge(1)` (regular dodge) makes it behave just like `geom_line` where data are connected by their order on the x axis. – CrunchyTopping Sep 27 '19 at 14:48