Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_line() arrow direction between specific values

Tags:

r

ggplot2

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.

like image 944
KNN Avatar asked Jun 15 '26 09:06

KNN


1 Answers

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")))

enter image description here

Note that the shape argument needs to be inside the aes() if you want a different shape for each year.

like image 112
Andrew Gustar Avatar answered Jun 18 '26 00:06

Andrew Gustar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!