Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

r - Add colored arrow to axis of ggplot2 (partially outside plot region)

I'd like to add a colored arrow (full length of the axis) to show time moving a in a direction (this can be assumed but for this plot there are no numeric values so I want the arrow to show the direction). I can use geom_segment to plot it but the part outside of the plot region is missing.

I've seen this post: R & ggplot2: How to get arrows under the axis label? but this solution is a hack of the axis title. This post: https://stackoverflow.com/a/10542622/1000343 shows lines outside text region 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"))) 

Giving

enter image description here

But I want

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem appears just to be the clipping region (as answered here). Try:

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)

to get

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...