本文介绍了ggplot2构面标签-不显示第二行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,用于生成带有多行带状文本的多面图.但是,这不再起作用了.以下是MWE,应从中解析带状文本,例如"bold(A)\ nallyally〜long〜extra" 发送至:

I have a script that used to produce a facetted plot with strip text on multiple lines. But this does not work anymore. Below is a MWE where the strip text should be parsed from, e.g. "bold(A)\nreally~long~extra" to:

您可以通过调试功能看到第二行.我什至提高了利润率,但无济于事...

The second line is cut off as you can see via the debug function. I even increased the margins but to no avail...

有什么问题吗?

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()的解决方案不再起作用.请查看其他问题,也许您也可以帮我吗?

And while we are at it, I only came up with this workaround because my previous solution of using label_bquote() does not work anymore. Please have a look at this other question, maybe you can help me with this, too?

推荐答案

不确定是否适合您.但是,达到预期结果的一种方法是使用 ggtext 包,该包允许您使用HTML和CSS设置方面标签的样式.为此, ggtext 引入了一个新的主题元素 element_markdown .试试这个:

Not sure wether this works for you. But one way to achieve the desired result would be to make use of the ggtext package, which allows you to style your facet labels using HTML and CSS. To this end ggtext introduces a new theme element element_markdown. Try this:

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

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

And for the second question in your former post a solution might look like so:

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

这篇关于ggplot2构面标签-不显示第二行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:19