gpt4 book ai didi

r - 防止在ggplot2中居中多层标题

转载 作者:行者123 更新时间:2023-12-01 01:43:52 24 4
gpt4 key购买 nike

这是我之前的问题 ( getting constant text size while using atop function in r ) 的第 2 部分。

现在的问题与我如何防止 plotmath 有关。使文本居中以避免额外的间距(此处以黄色突出显示)。我希望所有内容都与情节的右侧对齐。

(不幸的是,如果您的建议是这样,我不能用 substitute 替换 expression。)

有什么建议?

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

enter image description here

最佳答案

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

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

接下来我们有三层,也可以使用 substitute (据我所知,在您的情况下,只有第一个使用它)。
l1 <- substitute("layer1 is small")
l2 <- "layer2 is a bit longer"
l3 <- "layer3 is super-duper longgggggggg"

现在坏消息是 push只有使用 mono 字体才能达到预期的效果,这不是 ggplot2 中的默认系列. SO 关于字体有多个问题,所以如果您愿意,也许您可​​以导入其他一些单色字体。
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"))

enter image description here

关于r - 防止在ggplot2中居中多层标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com