Get x-position of boxplot with dodge in ggplot

Viewed 748

Hey I'd like to access the exact positions of the boxplot when dodging is applied as in the case below:

testPlot <- ggplot(iris, aes(x=Species, y=Sepal.Width, fill=Petal.Width > 1)) +
  geom_boxplot(position="dodge")
testPlot

enter image description here

This is important for instance so that one can add annotation directly above one box without fiddling. I can't find anything in str(testPlot).

1 Answers

Inspecting the output of ggplot_build(testPlot) can give you the data used to plot the boxplot. Here is the output.

# $data[[1]]
# fill ymin lower middle upper ymax      outliers notchupper notchlower      x PANEL group ymin_final ymax_final  xmin  xmax weight colour size alpha shape linetype
# 1 #F8766D  2.9  3.20    3.4 3.675  4.2      4.4, 2.3   3.506137   3.293863 1.0000     1     1        2.3        4.4 0.625 1.375      1 grey20  0.5    NA    19    solid
# 2 #00BFC4  2.3  2.70    2.9 3.000  3.4           2.2   2.972284   2.827716 2.1875     1     3        2.2        3.4 2.000 2.375      1 grey20  0.5    NA    19    solid
# 3 #F8766D  2.0  2.25    2.4 2.500  2.7                 2.549296   2.250704 1.8125     1     2        2.0        2.7 1.625 2.000      1 grey20  0.5    NA    19    solid
# 4 #00BFC4  2.5  2.80    3.0 3.175  3.6 3.8, 2.2, 3.8   3.083792   2.916208 3.0000     1     4        2.2        3.8 2.625 3.375      1 grey20  0.5    NA    19    solid
# -------------------------------------------------------------------------

Using such information for example, we can annotate a text on top of the [1] boxplot at a particular location as follows

testPlot + annotate(geom="text", x=1, y=3.3, label="Sample Text here",
                    color="blue")

How did I find the coordinate (1,3.3)? If you see closely the first row, you can see that the lower line (Q1) aka first quartile at 3.20 and y is between 2.9 and 4.2. You can also see the value of the outliers. The x value is between 0.625 and 1.375. You can follow the same principle and annotate the desired boxplot.

Output

sample_out

Hope that helps.

Related