Search code examples
rggplot2expression

make a portion of ggplot legend bold


I want to make a portion of my legend labels (which are stored in a separate data.frame). This question is related but it is simpler than my case:

library(tidyverse)
df <- data.frame(xx = c(0, 3),
                 yy = c(0, 1))

df_text <- data.frame(start = c(0, 1, 2),
                      end = c(1, 2, 3),
                      heading_bold = c("title 1", "title 2", "title 3"),
                      normal_text = c("i want this to be normal text title 1",
                                      "i want this to be normal text title 2",
                                      "i want this to be normal text title 3")) %>% 
  mutate(merged_text = paste0(heading_bold, ": ", normal_text)) #%>% 
  # perhaps I should try and make bold here?
  #mutate(merged_text = paste0("bold(", heading_bold, ")", ": ", normal_text))

ggplot(df, aes(x = xx, y = yy)) +
  geom_rect(data = df_text,
            aes(xmin = start,
                xmax = end,
                fill = merged_text,
                ymin = 0,
                ymax = 1),
            inherit.aes = FALSE) +
  scale_fill_viridis_d(option = "A", name = "Legend", limits = unique(df_text$merged_text), direction = -1) 

enter image description here

I want title 1, title 2 and title 3 to be bold within the legend.

As I have suggested above in the commented out code, one possible way to do this might be to wrap the text in bold function:

mutate(merged_text = paste0("bold(", heading_bold, ")", ": ", normal_text))

but I do not know how to call the expression further down.

Any ideas?

Thanks


Solution

  • Using ggtext you can apply markdown to your legend labels. In this example I flank the titles when concatenating the merged_text with ** and apply element_markdown() to the plot theme.

    library(tidyverse)
    library(ggtext)
    df <- data.frame(xx = c(0, 3),
                     yy = c(0, 1))
    
    df_text <- data.frame(start = c(0, 1, 2),
                          end = c(1, 2, 3),
                          heading_bold = c("title 1", "title 2", "title 3"),
                          normal_text = c("i want this to be normal text title 1",
                                          "i want this to be normal text title 2",
                                          "i want this to be normal text title 3")) %>% 
      mutate(merged_text = paste0("**",heading_bold,"**: ", normal_text)) 
    
    ggplot(df, aes(x = xx, y = yy)) +
      geom_rect(data = df_text,
                aes(xmin = start,
                    xmax = end,
                    fill = merged_text,
                    ymin = 0,
                    ymax = 1),
                inherit.aes = FALSE) +
      scale_fill_viridis_d(option = "A", name = "Legend", limits = unique(df_text$merged_text), direction = -1) +
      theme(legend.text = element_markdown())
    

    Created on 2024-06-14 with reprex v2.1.0