Esme_
Esme_

Reputation: 1520

Arrows showing direction of path on every nth data point in R ggplot2 plot

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

Upvotes: 0

Views: 644

Answers (1)

Roman
Roman

Reputation: 17648

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

Upvotes: 0

Related Questions