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:
Update: Be sure to see this related Stackoverflow Q&A if you need to save the plot with ggsave() and have the brackets persist in the saved image.
The OP requested the bracket be off the plot. This solution uses axis.ticks.length
in combination with axis.ticks = element_blank()
to allow the brace to be outside the plotting area.
This answer builds upon those of @Pankil and @user697473: we will use pBrackets
R package -- and include pictures!
library(ggplot2)
library(grid)
library(pBrackets)
x <- c(runif(10),runif(10)+2)
y <- c(runif(10),runif(10)+2)
the_plot <- qplot(x=x,y=y) +
scale_x_continuous("",breaks=c(.5,2.5),labels=c("Low types","High types") ) +
theme(axis.ticks = element_blank(),
axis.ticks.length = unit(.85, "cm"))
#Run grid.locator a few times to get coordinates for the outer
#most points of the bracket, making sure the
#bottom_y coordinate is just at the bottom of the gray area.
# to exit grid.locator hit esc; after setting coordinates
# in grid.bracket comment out grid.locator() line
the_plot
grid.locator(unit="native")
bottom_y <- 284
grid.brackets(220, bottom_y, 80, bottom_y, lwd=2, col="red")
grid.brackets(600, bottom_y, 440, bottom_y, lwd=2, col="red")
A quick note on @Pankil's answer:
## Bracket coordinates depend on the size of the plot
## for instance,
## Pankil's suggested bracket coordinates do not work
## with the following sizing:
the_plot
grid.brackets(240, 440, 50, 440, lwd=2, col="red")
grid.brackets(570, 440, 381, 440, lwd=2, col="red")
## 440 seems to be off the graph...
And a couple more to showcase functionality of pBrackets
:
#note, if you reverse the x1 and x2, the bracket flips:
the_plot
grid.brackets( 80, bottom_y, 220, bottom_y, lwd=2, col="red")
grid.brackets(440, bottom_y, 600, bottom_y, lwd=2, col="red")
## go vertical:
the_plot
grid.brackets(235, 200, 235, 300, lwd=2, col="red")
grid.brackets(445, 125, 445, 25, lwd=2, col="red")