Search code examples
rggplot2tidytext

bold an item in axis label after using reorder_within


I am using the reorder_within() function from the tidytext package in R to make a plot of different frequencies. An analogous example comes from here.

library(tidytext)

top_names %>%
    group_by(decade) %>%
    top_n(15) %>%
    ungroup %>%
    mutate(decade = as.factor(decade),
           name = reorder_within(name, n, decade)) %>%
    ggplot(aes(name, n, fill = decade)) +
    geom_col(show.legend = FALSE) +
    facet_wrap(~decade, scales = "free_y") +
    coord_flip() +
    scale_x_reordered() +
    scale_y_continuous(expand = c(0,0)) +
    labs(y = "Number of babies per decade",
         x = NULL,
         title = "What were the most common baby names in each decade?",
         subtitle = "Via US Social Security Administration")

The output image is:

How would I go about bolding an individual item in each facet? For example, if I wanted to bold the name David on each of the facets' axis labels, how would I go about doing this?


Solution

  • In contrast to the solutions in the answer linked by @tamtam, here is a solution that requires minimal overhead: You can use ggtext::element_markdown to interpret any text in the ggplot as markdown. Just add axis.text.y = ggtext::element_markdown() and all variable names that have the form "**Name**" are shown in bold:

    library(ggplot2)
    library(dplyr)
    library(tidytext)
    
    test_data <- data.frame(
      decade = rep(c("1950", "1960", "1970", "1980"), each = 3),
      name = rep(c("Max", "**David**", "Susan"), 4),
      n = c(2, 1, 4, 5, 3, 1, 5, 7, 10, 4, 5, 3)
    )
    
    
    test_data %>%
      group_by(decade) %>%
      ungroup %>%
      mutate(decade = as.factor(decade),
             name = reorder_within(name, n, decade)) %>%
      ggplot(aes(name, n, fill = decade)) +
      geom_col(show.legend = FALSE) +
      facet_wrap(~decade, scales = "free_y") +
      coord_flip() +
      scale_x_reordered() +
      scale_y_continuous(expand = c(0,0)) +
      labs(y = "Number of babies per decade",
           x = NULL,
           title = "What were the most common baby names in each decade?",
           subtitle = "Via US Social Security Administration") +
      theme(axis.text.y = ggtext::element_markdown())
    

    Created on 2020-09-22 by the reprex package (v0.3.0)