代码之家  ›  专栏  ›  技术社区  ›  user63230

将ggplot图例的一部分加粗

  •  1
  • user63230  · 技术社区  · 2 年前

    我想制作一部分图例标签(存储在单独的 data.frame ). 这 question 是相关的,但它比我的情况更简单:

    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

    我想要 title 1 , title 2 title 3 在传说中大胆一点。

    正如我在上面注释掉的代码中所建议的那样,一种可能的方法可能是将文本包装在 bold 作用

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

    但我不知道该怎么称呼这个表达。

    有什么想法吗?

    谢谢

    1 回复  |  直到 2 年前
        1
  •  1
  •   Seth    2 年前

    使用 ggtext 您可以对图例标签应用markdown。在这个例子中,当连接 merged_text 具有 ** 并申请 element_markdown() 到情节主题。

    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())
    

    创建于2024-06-14 reprex v2.1.0