【问题标题】:ggplot2 facet labels - second line is not displayedggplot2 刻面标签 - 不显示第二行
【发布时间】:2020-09-02 17:33:22
【问题描述】:

我有一个脚本,用于生成多行带有条形文本的多面图。但这不再起作用了。下面是一个 MWE,应该从中解析条形文本,例如"bold(A)\nreally~long~extra"转:

A
真的很长的额外

第二行被截断,你可以通过调试功能看到。我什至增加了利润,但无济于事......

任何想法是什么问题?

exmpl = data.frame(a = 1:100,
               b = rep(1:5, 20),
               f = factor(rep(LETTERS[1:5], each = 20))) %>% 
  as_tibble() %>% 
  mutate(f2 = paste0("bold(",f, ")\nreally~long~extra"))

ggplot(exmpl, aes(x = b, y = a)) +
  facet_grid(. ~ f2, labeller = label_parsed) +
  geom_point() +
  theme(strip.text.x = element_text(size = 10, hjust = 0, margin = margin(.5, 0, .5, 0, "cm"), debug = T))

编辑:

当我们这样做时,我只是想出了这个解决方法,因为我之前使用 label_bquote() 的解决方案不再有效。请看看this other question,也许你也可以帮助我?

【问题讨论】:

    标签: r ggplot2 label facet-grid ggtext


    【解决方案1】:

    不确定这是否适合您。但实现所需结果的一种方法是使用 ggtext 包,它允许您使用 HTML 和 CSS 设置构面标签的样式。为此ggtext 引入了一个新的主题元素element_markdown。试试这个:

    library(ggplot2)
    library(dplyr)
    
    exmpl = data.frame(a = 1:100,
                       b = rep(1:5, 20),
                       f = factor(rep(LETTERS[1:5], each = 20))) %>% 
      as_tibble() %>% 
      mutate(f2 = paste0("<b>", f, "</b><br>", "really long extra"))
    
    
    ggplot(exmpl, aes(x = b, y = a)) +
      facet_grid(. ~ f2) +
      geom_point() +
      theme(strip.text.x = ggtext::element_markdown(size = 10, hjust = 0))
    

    对于您之前帖子中的第二个问题,解决方案可能如下所示:

    mylabel <- function(x) {
      mutate(x, Species = paste0(letters[Species], " <i>", Species, "</i>"))
    }
    
    p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
    
    p + facet_grid(. ~ Species, labeller = mylabel) +
      theme(strip.text.x = ggtext::element_markdown())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-16
      • 2016-12-16
      • 1970-01-01
      • 2021-06-26
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      相关资源
      最近更新 更多