2

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.

enter image description here

2
  • geom fonts aren't in theme, you set them in the layer directly. Add family = "mono" as an argument to your stat_summary() Commented Jun 10, 2022 at 1:33
  • @GregorThomas - thanks! that worked. I modified it like this: stat_summary(fun.data = counts, geom = "text", family = "mono", size = 3). Size seems to mean something different here compared to when it is used in theme(). Do you want to add your comment as an answer? Then I will mark it as accepted. Commented Jun 10, 2022 at 1:42

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.