我正在制作一个类似于坡度图的图表,我想在一侧或两侧放置标签,并留有足够的空白空间以使其适合两侧。在标签很长的情况下,我将它们包裹起来stringr::str_wrap
用于放置换行符。为了防止标签重叠,我使用ggrepel::geom_text_repel
withdirection = "y"
所以 x 位置是稳定的,但 y 位置相互排斥。我还必须hjust = "outward"
在其右端对齐左侧文本,反之亦然。
但是,似乎排斥定位将标签的边界框放置在 中hjust = "outward"
,但该标签中的文本具有,即文本在其边界内居中。hjust = 0.5
直到现在,我从未注意到这一点,但是使用包裹标签,第二行居中尴尬,而我希望看到两行左对齐或右对齐。
这是一个基于数据集构建的示例mpg
。
library(ggplot2)
library(dplyr)
library(ggrepel)
df <- structure(list(long_lbl = c("chevrolet, k1500 tahoe 4wd, auto(l4)",
"chevrolet, k1500 tahoe 4wd, auto(l4)", "subaru, forester awd, manual(m5)",
"subaru, forester awd, manual(m5)", "toyota, camry, manual(m5)",
"toyota, camry, manual(m5)", "toyota, toyota tacoma 4wd, manual(m5)",
"toyota, toyota tacoma 4wd, manual(m5)", "volkswagen, jetta, manual(m5)",
"volkswagen, jetta, manual(m5)"), year = c(1999L, 2008L, 1999L,
2008L, 1999L, 2008L, 1999L, 2008L, 1999L, 2008L), mean_cty = c(11,
14, 18, 20, 21, 21, 15, 17, 33, 21)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -10L))
df_wrap <- df %>%
mutate(wrap_lbl = stringr::str_wrap(long_lbl, width = 25))
ggplot(df_wrap, aes(x = year, y = mean_cty, group = long_lbl)) +
geom_line() +
geom_text_repel(aes(label = wrap_lbl),
direction = "y", hjust = "outward", seed = 57, min.segment.length = 100) +
scale_x_continuous(expand = expand_scale(add = 10))
的其他值也会发生同样的情况hjust
。查看函数的source,我看到一条指向此问题的行:
hjust = x$data$hjust %||% 0.5,
如果为空,%||%
则分配 0.5 。x$data$hjust
据我所知,但似乎hjust
我设置的并没有被转移到这个位置,而是变成了空值。
我错过了什么吗?谁能在不重新实现整个算法的情况下看到我可以在哪里覆盖它?还是这里有一个错误会导致我的hjust
?