axis.text 字体系列和字体大小的有条件更改会产生不需要的 'gap'

Conditional change of axis.text font family and font size creates unwanted 'gap'

我需要根据条件更改条形图的特定 x 轴元素的族和大小。

我可以成功修改使用:

library(ggplot2)
ggplot(iris, aes(Species, Petal.Length)) + 
  geom_boxplot() + 
  coord_flip() +
  theme(axis.text.y = element_text(face = ifelse(levels(iris$Species)=="setosa","bold","italic")))

根据以下建议:

但是,由于某些原因,当我尝试应用 familysize 时,在轴和名称之间创建了一个空白间隙。

ggplot(iris, aes(Species, Petal.Length)) + 
  geom_boxplot() + coord_flip() + 
  theme(axis.text.y = element_text(family = ifelse(levels(iris$Species)=="setosa","sans","mono")))

ggplot(iris, aes(Species, Petal.Length)) + 
  geom_boxplot() + coord_flip() + 
  theme(axis.text.y = element_text(size = ifelse(levels(iris$Species)=="setosa", 10, 20)))

我尝试使用 margin 对其进行编辑,但是当修改名称时(例如使用闪亮的应用程序)可能会出现叠加。

这个差距是多少?我可以删除它吗?

我不知道为什么会这样。很奇特。但是你可以margin改变这个边距。
但是,您需要指定单位,例如作为 'inch'。然后找到正确的值是一个反复试验的问题,这也将在很大程度上取决于您的最终绘图输出。
也许找到不同的方法来突出显示数据会更安全、更容易?

library(ggplot2)

ggplot(iris, aes(Species, Petal.Length)) + 
  geom_boxplot() + 
  theme(axis.text.y = element_text(family =  
          ifelse(levels(iris$Species)=="setosa","sans","mono"),
        margin = margin(r = -2, l = 0.8, unit = 'in'))) +
  coord_flip()

reprex package (v0.3.0)

于 2020 年 1 月 15 日创建

问题已在即将发布的 ggplot2 3.3.0 中修复,但现在会触发警告,因为这种格式化轴文本的方法不可靠,将来可能随时停止工作。

library(ggplot2) # v 3.3.0 or higher

# discouraged, triggers warning message
ggplot(iris, aes(Species, Petal.Length)) + 
  geom_boxplot() + coord_flip() + 
  theme(
    axis.text.y = element_text(
      size = ifelse(levels(iris$Species)=="setosa", 10, 20)
    )
  )
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

作为替代方案,正在开发的 ggtext 包试图通过将格式化指令编码到文本标签中来提供解决此问题的主要方法。

library(ggtext) # remotes::install_github("clauswilke/ggtext")
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(glue)
#> 
#> Attaching package: 'glue'
#> The following object is masked from 'package:dplyr':
#> 
#>     collapse

iris %>%
  mutate(
    Species = ifelse(
      Species == "setosa",
      "<span style = 'font-size:10pt'>setosa</span>",
      glue("<span style = 'font-size:20pt'>{Species}</span>")
    )
  ) %>%
  ggplot(aes(Species, Petal.Length)) + 
  geom_boxplot() + coord_flip() + 
  theme(axis.text.y = element_markdown())

reprex package (v0.3.0)

于 2020 年 1 月 16 日创建