I'm trying to do something similar to this post here, connect points based on grouping (in this case, site) with an arrow and specify the arrow direction based on specific value (year). I can't get the direction of the arrow to work correctly. I want to always have the direction of the arrow go from 2017 to 2018 (for each different site). Below is my code so far and sample data (which is sample first 4 rows output from an ordination).
ggplot() +
geom_point(data = data.scores[1:4,], aes(x = NMDS1, y = NMDS2),
shape = year[1:4]) +
geom_line(data = data.scores[1:4,], aes(x=NMDS1, y=NMDS2, group = site),
arrow = arrow(length = unit(0.15, "cm")))
Sample data would look like this:
>data.scores
NMDS1 NMDS2 site year
1 -0.009286247 -0.009874382 1 2018
2 -0.099650245 0.021869952 1 2017
3 0.034465891 0.043034188 2 2018
4 0.040777968 0.028120489 2 2017
So the output for this would be an arrow from point 2 (site 1, year 2017) to point 1 (site 1, year 2018). I've seen a number of similar posts but can't quite figure this out so thank you.
One way would be to sort the data by year and use geom_path rather than geom_line, which plots in data order rather than in order of the x variable.
library(dplyr) #for arrange and %>%
library(ggplot2)
data.scores %>%
arrange(year) %>% #sort ascending so that 2018 is plotted last
ggplot() +
geom_point(aes(x = NMDS1, y = NMDS2, shape = factor(year)),
size = 3) + #I've made it bigger so you can see it better!
geom_path(aes(x = NMDS1, y = NMDS2, group = site),
arrow = arrow(length = unit(0.55, "cm")))

Note that the shape argument needs to be inside the aes() if you want a different shape for each year.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With