ggplot2: Curly braces on an axis?

前端 未结 5 1245
执笔经年
执笔经年 2020-11-28 09:30

In answering a recent visualization question I really needed braces to show a span on an axis, and I can\'t figure out how to do it in ggplot2. Here\'s the plot:

5条回答
  •  迷失自我
    2020-11-28 09:51

    as @user697473 suggested pBrackets is the elegant solution.

    It works best with the default plotting commands but to make it work with GGplot2 use the pBracket::grid.brackets. I'm including the code to make it easy for try it out.

    Starting with your code..

    library(ggplot2)
    x <- c(runif(10),runif(10)+2)
    y <- c(runif(10),runif(10)+2)
    qplot(x=x,y=y) +
      scale_x_continuous("",breaks=c(.5,2.5),labels=c("Low types","High types") ) +
      theme(axis.ticks = element_blank())
    

    the last line removes the ticks you didn't want.
    Now the pBrackets

    library(pBrackets)  # this will also load grid package
    grid.locator(unit="native") 
    

    now using your cursor identify the point on the graph where the brackets start and end. You will get the corresponding coordinates in the 'native' unit. now feed them in the command below

    grid.brackets(240, 440, 50, 440, lwd=2, col="red")
    grid.brackets(570, 440, 381, 440, lwd=2, col="red")
    

    You can add the brackets anywhere on the graph or even add text using grid.text.

    Hope this helps! Thank you pBrackets!

    Pankil!

提交回复
热议问题