防止在ggplot2中将多层标题居中 [英] preventing centering multilayered caption in ggplot2

查看:138
本文介绍了防止在ggplot2中将多层标题居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前的问题的第二部分(

This is part-2 to my previous question (getting constant text size while using atop function in r).

现在,问题与我如何防止plotmath将文本居中以避免多余的空格有关(此处以黄色突出显示)有关.我希望所有内容都与图的右侧对齐.

Now the issue relates to how I can prevent plotmath from centering the text to avoid the extra spacing (highlighted here in yellow). I want everything aligned to the right side of the plot.

(很遗憾,如果您的建议是这样,我不能用expression代替substitute.)

(Unfortunately, I can't replace substitute with expression if that's what your suggestion is going to be.)

有什么建议吗?

library(ggplot2)

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_boxplot()  +
  labs(caption = substitute(atop(
    atop(
      displaystyle("layer1 is small"),
      displaystyle("layer2 is a bit longer")
    ),
    "layer3 is super-duper longgggggggg"
  )))

推荐答案

让我们从好消息开始.这是一个向from添加足够的前导空格的函数,其长度与列表to中最长的元素的长度一样:

Let's start with good news. Here's a function that adds enough leading spaces to from as to be as long as the longest element from the list to:

push <- function(from, to)
  sprintf(paste("%", max(nchar(from), max(nchar(to))), "s"), from)

接下来,我们有三层,也可以使用substitute(据我了解,在您的情况下,只有第一层使用它).

Next we have three layers, which also may use substitute (as I understand, in your case only the first one uses it).

l1 <- substitute("layer1 is small")
l2 <- "layer2 is a bit longer"
l3 <- "layer3 is super-duper longgggggggg"

现在,坏消息是push仅使用单色字体才能达到所需的效果,这不是ggplot2中的默认字体.关于字体,SO上存在多个问题,因此,如果您愿意,也许您可​​以导入其他一些单色字体.

Now the bad news is that push achieves the desired effect only with mono fonts, which is not the default family in ggplot2. There are multiple question on SO regarding fonts, so perhaps you may import some other mono font, if you prefer.

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_boxplot()  +
  labs(caption = substitute(atop(atop(textstyle(l1), textstyle(l2)), textstyle(l3)), 
                            list(l1 = push(l1, list(l2 ,l3)),
                                 l2 = push(l2, list(l1, l3)), 
                                 l3 = push(l3, list(l2, l3))))) +
  theme(plot.caption = element_text(family = "mono"))

这篇关于防止在ggplot2中将多层标题居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆