0
votes

I'm trying to color code arrows based on their direction using geom_path in ggplot2. I have multiple years of data in individual rows and want an arrow pointing from the earliest data point to the most recent, with color depicting the direction to make it even easier to interpret. The points are grouped by Lake_ID, and because there are multiple rows for each year I'm having trouble.

Here's the basic data:

    Lake_ID Year    Gear    psd BioVolume
    16  2012    EF  0.370967742 0.095585695
    16  2012    GN  1   0.095585695
    16  2012    TN  0   0.095585695
    16  2012    Whole   0.375   0.095585695
    16  2017    EF  0.214285714 0.100623115
    16  2017    GN  1   0.100623115
    16  2017    TN  0   0.100623115
    16  2017    Whole   0.179487179 0.100623115

Basic Graph

    ggplot(blg.dup.year,aes(BioVolume,psd,group=Lake_ID,label=Year))+
        geom_point(aes(BioVolume,psd,colour=Year))+theme_bw()+
        facet_grid(Gear~.,scales = "free_y")+
        labs(title="Bluegill PSD",y="PSD",x="Littoral BioVolume")+
        geom_path(arrow=arrow(angle=30,length=unit(0.1,"inches"),
            type="closed"),aes(group=Lake_ID))

Thanks!

1

1 Answers

0
votes

Assuming that what you mean by direction is whether the arrow is pointing up or down here is one solution. Assign your original plot to a variable:

p1 <- ggplot(blg.dup.year,aes(BioVolume,psd,group=Lake_ID,label=Year))+
  geom_point(aes(BioVolume,psd,colour=Year))+theme_bw()+
  facet_grid(Gear~.,scales = "free_y")+
  labs(title="Bluegill PSD",y="PSD",x="Littoral BioVolume")+
  geom_path(arrow=arrow(angle=30,length=unit(0.1,"inches"),
                        type="closed"),aes(group=Lake_ID))

Get data from layers (your arrows are the second geom):

arrow_data <- layer_data(p1, 2) 

Get the directions from the y axis and then assign a color based on the sign:

directions <- diff(arrow_data$y)[seq(1,nrow(arrow_data),2)]
colors <- case_when(sign(directions) == -1 ~ "red",
                    sign(directions) == 0 ~ "orange",
                    sign(directions) == -1 ~ "green", 
                    TRUE ~ "grey50")

You need to double the colors as ggplot requires a color for start and finish points.

colors <- rep(colors,each = 2)

And finally just add the color to the geom:

ggplot(blg.dup.year,aes(BioVolume,psd,group=Lake_ID,label=Year))+
   geom_point(aes(BioVolume,psd,colour=Year))+theme_bw()+
   facet_grid(Gear~.,scales = "free_y")+
   labs(title="Bluegill PSD",y="PSD",x="Littoral BioVolume") +
   geom_path(arrow=arrow(angle=30,length=unit(0.1,"inches"),
                         type="closed"),aes(group=Lake_ID), color = colors)

So for your example you would get:

enter image description here