8

I am using ggplot2 in R to produce a scatter graph of ordered points in a dataframe joined by a continuous line. On this line I would like to place several arrowheads that show the order of the points in the dataframe. I can place an arrow between each adjoining point, as shown below, but as I add more points the graph becomes crowded with arrowheads and messy. Is there a way that I can place arrowheads between every 2, 3, 4.. adjoining points?

library(ggplot2)  
library(grid)

b = c(1,2,3,6,7,5,4,3,2,3,4,6,8,9,9,8,9,11,12)
c = c(2,3,2,4,4,6,8,7,5,4,3,5,9,9,8,8,10,11,15)
df = data.frame(b, c)

ggplot(df, aes(x=b, y= c)) +
    geom_point() +
    geom_segment(aes(xend=c(tail(b, n=-1), NA), yend=c(tail(c, n=-1), NA)),
                 arrow=arrow(length=unit(0.4,"cm"), type = "closed"))

Example graph: enter image description here

zx8754
  • 52,746
  • 12
  • 114
  • 209
RoachLord
  • 993
  • 1
  • 14
  • 28

1 Answers1

3

Here is my suggestion

# add columns which have values only in rows you want arrows for
df$d<-NA
df$d[2:4]<-df$b[2:4]
df$e<-NA
df$e[2:4]<-df$c[2:4]
# and then plot
ggplot(df, aes(x=b, y= c)) +
    geom_point() +

    geom_segment(aes(xend=c(tail(b, n=-1), NA), yend=c(tail(c, n=-1), NA)),
                  )+
    geom_segment(aes(xend=c(tail(d, n=-1), NA), yend=c(tail(e, n=-1), NA)),
                 arrow=arrow(length=unit(0.4,"cm"),type = "closed")
                 )

enter image description here

Tomas H
  • 713
  • 4
  • 10
  • 1
    Yeah, I agree this is a solution and I guess this is in keeping with layering in the grammar of graphics but it seems a shame to have partially duplicate columns of data in the dataframe. – RoachLord Jun 07 '16 at 14:20