英文:
Proper way to pass vectorized input to element_text?
问题
我经常发现自己想根据它们的位置以不同方式对齐我的绘图的x轴标签,将左侧的值左对齐,将右侧的值右对齐。然而,element_text
不支持官方的向量化输入(也永远不会支持吗?),所以我想知道如何以适当的ggplot2
方式解决这个问题。
问题:x轴标签重叠(并在最右侧截断)
library(ggplot2)
v <- data.frame(x=1:2, y=1:2, facet=gl(2, 2))
gp <- ggplot(v) +
geom_point(aes(x=x, y=y)) +
scale_x_continuous(breaks = 1:2, labels = c("Minimum", "Maximum")) +
facet_wrap(~facet)
gp
我的解决方案:
gp + theme(axis.text.x = element_text(hjust=c(0, 1)))
但是:
警告消息:
`element_text()`的向量化输入没有官方支持。
ℹ 结果可能出乎意料或在ggplot2的未来版本中更改。
如果不支持向量化element_text
,正确的方式是如何以不同方式对齐ggplot中的文本?
英文:
I often find myself wanting to align the x-axis labels on my plots differently based on their location, with values on the left left-aligned and values on the right, right-aligned. However, element_text
doesn't have official support for vectorized input (and never will?) so I'm wondering how to solve this in proper ggplot2
fashion.
The problem: overlapping x-axis labels (and truncated on the far right)
library(ggplot2)
v <- data.frame(x=1:2, y=1:2, facet=gl(2, 2))
gp <- ggplot(v) +
geom_point(aes(x=x, y=y)) +
scale_x_continuous(breaks = 1:2, labels = c("Minimum", "Maximum")) +
facet_wrap(~facet)
gp
My solution:
gp + theme(axis.text.x = element_text(hjust=c(0, 1)))
Except:
Warning message:
Vectorized input to `element_text()` is not officially supported.
ℹ Results may be unexpected or may change in future versions of ggplot2.
What's the correct way to differently-align text in a ggplot if vectorized element_text
isn't supported?
答案1
得分: 4
Claus Wilke 在这里 表示他的 ggtext 包支持以这种方式使用向量,而且将来也会继续支持。正如 thomasp85(Thomas Lin Pedersen)在该帖子中所说:“FWIW,我认为这种 hack 的大多数用例可以使用 element_markdown() 正确解决”,即。
library(ggplot2)
library(ggtext)
v <- data.frame(x=1:2, y=1:2, facet=gl(2, 2))
gp <- ggplot(v) +
geom_point(aes(x=x, y=y)) +
scale_x_continuous(breaks = 1:2, labels = c("Minimum", "Maximum")) +
facet_wrap(~facet)
gp
<!-- -->
gp +
theme(axis.text.x = element_markdown(hjust = c(0, 1)))
<!-- -->
<sup>Created on 2023-04-11 with reprex v2.0.2</sup>
英文:
Claus Wilke states here that his ggtext package does support the use of vectors in this way and it will continue supporting it in the future. As thomasp85 (Thomas Lin Pedersen) says in the thread "FWIW, I think most of the use cases for this hack can be solved properly using element_markdown()", i.e.
library(ggplot2)
library(ggtext)
v <- data.frame(x=1:2, y=1:2, facet=gl(2, 2))
gp <- ggplot(v) +
geom_point(aes(x=x, y=y)) +
scale_x_continuous(breaks = 1:2, labels = c("Minimum", "Maximum")) +
facet_wrap(~facet)
gp
<!-- -->
gp +
theme(axis.text.x = element_markdown(hjust = c(0, 1)))
<!-- -->
<sup>Created on 2023-04-11 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论