Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ggplot how to control fonts on boxplot with stat

How do I control the font-family and size for text elements added to my boxplot:

Following the approach in this question, I have implemented the following code to show the number of observations:

library("ggplot2")

v_min <- -1
v_max <- 3.5
increm <- 0.5
y_limits <- c(v_min, v_max)
increms <- seq(v_min, v_max, increm)


counts <- function(x){
  # you can experiment with 'adjust' and 'max-value' to find the perfect position
  adjust <- 0.95
  return(c(y = adjust * v_max, label = length(x))) 
  
}

ggplot(d1, aes(x = ONRC_Hierarchy, y=lwpMeanRut_inc)) +
    geom_boxplot(outlier.alpha = 0.2, outlier.size = 0.5) + 
    geom_hline(aes(yintercept=0), color="blue", linetype="dotted", size=1)+
    stat_summary(fun.data = counts, geom = "text") +
    scale_y_continuous(limits = y_limits, breaks = increms) + 
    xlab("") +
    ylab("Rut Increment (mm/year)\n") + 
    theme_minimal() + 
    theme(
          text = element_text(size = 10, family = "mono"),
          axis.text.x=element_text(angle = -35, hjust = 0),
          panel.grid.major.y = element_line(color = "lightgray",
                                        size = 0.15,linetype = 2),
          panel.grid.minor.y = element_blank(),
          panel.grid.major.x = element_blank())

This solution works, as shown in the plot below, except that the font is different from the other graph elements. As you can see, I have tried to control this with the theme() statement, but it does not seem to work. Note, I deliberately used a small mono font to show the difference in the number of observations labels and the other graph elements.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

Geom/stat fonts are set in the geom/stat layer, not in theme(). In this case, you can add family = "mono" as an argument to your stat_summary().

The size of fonts in geom_text/geom_label etc. is not on the same scale as element_text theme options, which are in points. You can read more about that here and here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading