我有一些y轴标签,我想拥有所有相同的间距.标签由2个变量组成,我想把正确的间距放在左边的变量左对齐,右边的变量是右对齐.我认为这是一个微不足道的任务,实际上在data.frame中这样做很容易使用stringi包中的字符串填充函数.但是,该图没有所需的对齐方式.
library(stringi)
library(tidyverse)
paster <- function(x, y, fill = ' '){
nx <- max(nchar(x))
ny <- max(nchar(y))
paste0(
stringi::stri_pad_right(x, nx, fill),
stringi::stri_pad_left(y, ny, fill)
)
}
plot_dat <- mtcars %>%
group_by(gear) %>%
summarize(
n = n(),
drat = mean(drat)
) %>%
mutate(
gear = case_when(
gear == 3 ~ 'three and free',
gear == 4 ~ 'four or more',
TRUE ~ 'five'
),
label = paster(gear, paste0(' (', n, ')'))
)
plot_dat
## # A tibble: 3 x 4
## gear n drat label
## <chr> <int> <dbl> <chr>
## 1 three and free 15 3.132667 three and free (15)
## 2 four or more 12 4.043333 four or more (12)
## 3 five 5 3.916000 five (5)
plot_dat %>%
ggplot(aes(x = drat, y = label)) +
geom_point()
Run Code Online (Sandbox Code Playgroud)
得到:
我想要的是:
Z.L*_*Lin 11
您的文本字符串基于等宽字体(这是R控制台使用的)很好地间隔开.
将轴标签的字体系列设置为等宽字体将提供正确的对齐:
ggplot(mtcars,
aes(x = drat, y = label)) +
geom_point() +
theme(axis.text.y = element_text(family = "mono"))
Run Code Online (Sandbox Code Playgroud)
(不是最漂亮的外观,我知道......但是你得到了基本的想法.我对R中的字体没有多少工作,这是我现在能想到的唯一的等宽字体.)