R & ggplot2: How to get arrows under the axis label?

后端 未结 3 692
走了就别回头了
走了就别回头了 2020-12-09 06:52


I\'m about to plot odds ratios with R/ggplot2 and I want to add two arrows underneath or next to the X-axis label. One pointing to the left, one pointing to the right,

3条回答
  •  北海茫月
    2020-12-09 07:14

    I'm doing a bit of guessing about what you want, exactly, as I'm not sure what you were attempting with geom_segment, whether that was part of your data, or an attempt to create an arrow. But you can build on geom_segment to get something like what you describe:

    #Your test data, with a small typo repaired
    dd <- data.frame(x = c("A","B","C","D","E","F","G","H","I"),
                     y = c(1.782,0.136,0.978,0.645,0.518,1.474,0.855,0.673,0.369))
    dd <- transform(dd, ylo = c(0.719,0.046,0.945,0.295,0.188,0.577,0.407,0.310,0.145), 
            yhi = c(4.420,0.398,1.012,1.411,1.424,3.768,1.798,1.460,0.940))
    
    #Create a separate data frame for the arrow labels
    arrowLab <- data.frame(lab = c("Increasing","Decreasing"),
                           x = c(0.15,0.15),y = c(10^0.25,10^(-0.25)))
    
    ggplot(data = dd, aes(x=ordered(x, levels=rev(x)), y=y)) +
            geom_pointrange(aes(ymin=ylo, ymax=yhi)) +
            geom_segment(aes(x = 0, xend = 0, y= 1, yend= 2),
                             arrow=arrow(length=unit(0.2,"cm"))) +
            geom_segment(aes(x = 0, xend = 0, y= 1, yend= 10^(-0.25)),
                             arrow=arrow(length=unit(0.2,"cm"))) +
            geom_text(data = arrowLab,aes(x=x,y=y,label = lab),size = 3) +
            coord_flip() +
            geom_hline(aes(yintercept=1), lty=2) +
            scale_y_log10() 
    

    enter image description here

    Note that I hard-coded much of the positioning, so you'll likely want to tinker with those values to get what you want, or you could try to choose them programmatically based on your data.

提交回复
热议问题