0

I want to use ggplot2 to create a path with arrows in a plot. However, I have a lot of data points and so I only want the arrow on every nth datapoint. I adapted this answer for every nth label to put an observation point every nth data point, but if I try to use this with path I get straight lines between these points. I just want the arrow head.

The MWE below shows my attempt to get the two paths working together (I do want the full path as a line), and what worked for points (that I want to be directional arrows). In my real data set the arrows will point in different directions (so I can't just use a static arrow head as the observation symbol). I am also working with other filtering within the plots, and so creating new data frames that only keep some points is not a convenient solution.

MWE

library(tidyverse)
library(tidyr)
library(dplyr)
 

x <- seq(from = -100, to = 100, by = 0.01)
y <- x^3 - 2 * x + x

df<- data.frame(x,y)
df$t<- seq(1:nrow(df))

ggplot(data = df, aes(x = x, y = y)) +
  geom_path(size = 0.1, aes(colour = t)) +
  geom_path(aes(colour = t),data = . %>% filter(row_number() %% 2000 == 0), arrow = arrow(type = 'open', angle = 30, length = unit(0.1, "inches")))

ggplot(data = df, aes(x = x, y = y)) +
  geom_path(size = 0.1, aes(colour = t)) +
  geom_point(aes(colour = t),data = . %>% filter(row_number() %% 2000 == 0))
Esme_
  • 1,360
  • 3
  • 18
  • 30
  • https://www.rdocumentation.org/packages/metR/versions/0.9.2/topics/geom_arrow – IRTFM Jun 30 '21 at 04:59
  • @IRTFM Thanks for the suggestion, but I can't figure out how to use this. I tried adding geom_arrow() to the plot in place of the second geom_path - but it just gave the error `could not find function geom_arrow`. The only examples I could find were field plots. – Esme_ Jun 30 '21 at 05:16
  • Top pf page says: "RDocumentation// metR (version 0.9.2)// geom_arrow: Arrows" so its in a different package. – IRTFM Jun 30 '21 at 17:25

1 Answers1

0

You can try to add a grouping variable.

ggplot(data = df, aes(x = x, y = y)) +
  geom_path(aes(colour = t, group =factor(gr)),data = . %>% filter(row_number() %% 2000 == 0) %>% 
              mutate(gr = gl(n()/2, 2)), 
            arrow = arrow(type = 'open', angle = 30, length = unit(0.1, "inches")))

enter image description here

Roman
  • 17,008
  • 3
  • 36
  • 49