左右对齐轴文本,各文本之间要有精确的间距 [英] Left and right align axis text with exact spacing between

查看:135
本文介绍了左右对齐轴文本,各文本之间要有精确的间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些y轴标签,我希望它们都具有相同的间距.标签由2个变量组成,我想在它们之间放置正确的间距,使左变量左对齐,右变量右对齐.我认为这是一项琐碎的任务,实际上,在data.frame中这样做很容易,使用 stringi 包中的字符串填充函数即可.但是,该图没有所需的对齐方式.

I have some y axis labels I want to have all the same spacing. The labels are composed of 2 variables and I'd like to put the correct spacing in between to the left variable is left aligned and the right variable is right aligned. I assumed this to be a trivial task and in fact doing so in a data.frame is easy using string padding functions from stringi package. However the plot does not have the desired alignment.

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

赠予:

我想要的是:

推荐答案

您的文本字符串根据 monospace 字体(R控制台使用的字体)很好地隔开了.

Your text strings are nicely spaced based on a monospace font (which is what R console uses).

将轴标签的字体系列设置为等宽字体将给出正确的对齐方式:

Setting the axis label's font family to a monospace font will give the correct alignment:

ggplot(mtcars,
       aes(x = drat, y = label)) +
  geom_point() +
  theme(axis.text.y = element_text(family = "mono"))

(不是最漂亮的外观,我知道...但是您了解了基本概念.我在R& amp;中使用字体的工作不多;这是我现在能想到的唯一的等宽字体.)

(Not the prettiest look, I know... But you get the basic idea. I haven't worked much with fonts in R & this is the only monospace font I can think of right now.)

这篇关于左右对齐轴文本,各文本之间要有精确的间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆