r - 将字符串函数应用于图中的(所有)实验室类型标签

标签 r ggplot2

我正在寻找一种将函数应用于指定标签或绘图中包含的所有标签的方法。目标是拥有从默认标签派生的简洁的人类可读标签,而无需指定每个标签。

为了演示我在输入变量名称和输出方面寻找的内容,我提供了一个基于 starwars 数据集的示例,该示例使用多功能 snakecase::to_sentence_case() 函数,但这可以适用于任何函数,包括以预定方式扩展短变量名称的函数:

library(tidyverse)
library(snakecase)

starwars %>%
  filter(mass < 1000) %>%
  mutate(species = species %>% fct_infreq %>%  fct_lump(5) %>% fct_explicit_na) %>%
  ggplot(aes(height, mass, color=species, size=birth_year)) +
  geom_point() +
  labs( 
    x = to_sentence_case("height"),
    y = to_sentence_case("mass"),
    color = to_sentence_case("species"),
    size  = to_sentence_case("birth_year")
  )

生成以下图表:

Star Wars Plot

该图是所需的输出,但需要手动指定每个标签,如果稍后更改变量,则会增加出错的可能性。请注意,如果我没有指定标签,所有标签都会自动应用,但使用变量名称而不是更漂亮的版本。

这个问题似乎与 labeller() 函数的用途有些相关,但它似乎只适用于分面。 this question 中提出了另一个相关问题。 。但是,这两个似乎仅适用于数据中包含的值,而不适用于绘图中使用的变量名称,这正是我正在寻找的.

最佳答案

@z-lin 的非常有用的答案向我展示了一种简单的方法,只需在打印之前修改绘图对象即可实现此目的。

借助 gg_apply_labs() 可以实现预期结果,这是一个简短的函数,它将对绘图对象的 $labels 应用任意字符串处理函数。生成的代码应该是此方法的独立说明:

# Packages    
library(tidyverse)
library(snakecase)

# This applies fun to each label present in the plot object
#
# fun should accept and return character vectors, it can either be a simple
# prettyfying function or it can perform more complex lookup to replace 
# variable names with variable labels
gg_apply_labs <- function(p, fun) {
  p$labels <- lapply(p$labels, fun)
  p
}

# This gives the intended result
# Note: The plot is assigned to a named variable before piping to apply_labs()
p <- starwars %>%
  filter(mass < 1000) %>%
  mutate(species = species %>% fct_infreq %>%  fct_lump(5) %>% fct_explicit_na) %>%
  ggplot(aes(height, mass, color=species, size=birth_year)) +
  geom_point()
p %>% gg_apply_labs(to_sentence_case)

# This also gives the intended result, in a single pipeline
# Note: It is important to put in the extra parentheses!
(starwars %>%
  filter(mass < 1000) %>%
  mutate(species = species %>% fct_infreq %>%  fct_lump(5) %>% fct_explicit_na) %>%
  ggplot(aes(height, mass, color=species, size=birth_year)) +
  geom_point()) %>% 
  gg_apply_labs(to_sentence_case)

# This DOES NOT give the intended result
# Note: The issue is probably order precedence
starwars %>%
  filter(mass < 1000) %>%
  mutate(species = species %>% fct_infreq %>%  fct_lump(5) %>% fct_explicit_na) %>%
  ggplot(aes(height, mass, color=species, size=birth_year)) +
  geom_point() %>% 
  gg_apply_labs(to_sentence_case)

关于r - 将字符串函数应用于图中的(所有)实验室类型标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032392/

相关文章:

r - 延长 ggplot2 中密度图的尾部

arrays - 3d 数组 R 中的 n 个前邻居列表

r - "gam"插入符号模型不返回fitting.values

调整 strip.background 的大小以匹配 ggplot facet_wrap 中的 strip.text

r - 如何在 R 中创建包含俄罗斯欧洲部分的欧洲 map ?

r - ggplot2:在循环中添加线条并保留颜色映射

r - 错误: stat_count() must not be used with a y aesthetic

r - 使用非标准评估迭代某些内部环境中定义的符号

r - 使用 R 中的函数调用对象

r - 拼凑中色标的水平对齐