我正在ggplot中创建森林图,并希望在y轴上显示每个研究的多个方面。为了使外观整洁,我希望每个研究的各个方面都保持一致。
我已经使用stringer在每个学习方面之间填充空格,然后将所有方面粘贴到单个字符串中以显示为y轴标签,但是当传递给ggplot时,我失去了这种对齐方式。我尝试了许多不同的填充策略(在左侧/右侧填充)并尝试使用hjust,但似乎每个方面都是根据hjust选项而不是整个字符串或其他东西对齐的
require(stringr)
require(tidyverse)
#Create data frame with studies and aspects of different lengths
df <- data.frame(study = c("study 1", "study 2 long name", "study 3", "study 4 superduper long name"),
aspect1 = c("aspect", "longer aspect", "aspect", "long aspect"),
aspect2 = c("superduper long aspect", "aspect", "long aspect", "longer aspect"),
estimate = c(2,3,4,3),
est_lo = c(2,3,4,3) - 1,
est_hi = c(2,3,4,3) + 1)
#Generate labels by padding each aspect and then pasting aspects together
df <- df %>%
mutate(labels = str_c(str_pad(study, 30, "right"),
str_pad(aspect1, 15, "left"),
str_pad(aspect2, 25, "left")))
#Plot with ggplot
df %>%
ggplot(aes(x = estimate, xmin = est_lo, xmax = est_hi, y = labels)) +
geom_point() +
geom_errorbarh(height = 0.2) +
theme(axis.ticks.y = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(hjust = 1))
我希望ggplot标签看起来像字符串的标签一样:
#look at labels as character strings to check alignment
df$labels
[1] "study 1 aspect superduper long aspect"
[2] "study 2 long name longer aspect aspect"
[3] "study 3 aspect long aspect"
[4] "study 4 superduper long name long aspect longer aspect"
但是ggplot似乎在用空白执行了一些意外操作,从而消除了对齐方式: