Add a colored arrow to the ggplot2 axis (partially off-site)

I would like to add a colored arrow (full length of the axis) to show the time moving a in the direction (this can be assumed, but there are no numerical values ​​for this graph, so I want the arrow to display the direction). I can use geom_segmentto build it, but there is no part outside the graph area.

I saw this message: R and ggplot2: How to get the arrows under the axis label? , but this solution is hacking the axis name. This post: https://stackoverflow.com/a/166268/128 shows lines outside the text area, but not a colored arrow.

MWE

library(ggplot2); library(grid); library(scales)

dat <- data.frame(Time=0:5, y=0:5)

ggplot(dat, aes(x=Time, y=y)) +
    geom_area(alpha=.1) + theme_bw() +
    scale_y_continuous(expand = c(0, 0)) +
    scale_x_continuous(expand = c(0, 0)) +
    theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank()
    )    

I tried:

ggplot(dat, aes(x=Time, y=y)) +
    geom_area(alpha=.1) + theme_bw() +
    scale_y_continuous(expand = c(0, 0)) +
    scale_x_continuous(expand = c(0, 0)) +
    theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank()
    ) +
    geom_segment(aes(x=0, xend = 5 , y=0, yend = 0), size=1.5,
        arrow = arrow(length = unit(0.6,"cm"))) 

To give

enter image description here

But I want

enter image description here

+4
2

, ( ). :

p1<-ggplot(dat, aes(x=Time, y=y)) +
    geom_area(alpha=.1) + theme_bw() +
    scale_y_continuous(expand = c(0, 0)) +
    scale_x_continuous(expand = c(0, 0)) +
    theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank()
    ) +
    geom_segment(aes(x=0, xend = 5 , y=0, yend = 0), size=1.5,
        arrow = arrow(length = unit(0.6,"cm"))) 

gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

enter image description here

+6

,

library(ggplot2)

element_grob.element_custom <- function(element, ...)  {
  grid::segmentsGrob(0,1,1,1, arrow = arrow())
}
 ## silly wrapper to fool ggplot2
axis_custom <- function(...){
  structure(
    list(...), # this ... information is not used, btw
    class = c("element_custom","element_blank", "element") # inheritance test workaround
  ) 

}

ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_line() +
  theme(axis.line = axis_custom(),
        axis.line.y=element_blank())

enter image description here

+7

All Articles