R语言 使用标注器更改面网格标签和面的顺序

e5nqia27  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(104)

有没有一种方法可以使用ggplot2中的labeller函数更改**标签和面的顺序?我可以单独做,但不能两者都做。

library(ggplot2)
facet.labs <- c("very old", "old", "new")
names(facet.labs) <- sort(unique(mtcars$gear))

# This successfully changes the labels
mtcars |> 
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(~gear, labeller = labeller(gear = facet.labs))

# This successfully changes the order of facets
mtcars |> 
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(~factor(gear, levels = c(5, 4, 3)))

# You would expect this to change both but it looks exactly like the one above, i.e. changed order but not labels
mtcars |> 
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(~factor(gear, levels = c(5, 4, 3)), labeller = labeller(gear = facet.labs))

我想要的是标签的顺序和名称“新”,“旧”,“非常旧”。

vshtjzan

vshtjzan1#

编辑1

我不认为有一种方法可以像这样使用labeller,对不起。也许你可以在你的facet_wrap()中将你的'gear'变量改为一个带标签的因子?例如

library(ggplot2)

facet.labs <- c("very old", "old", "new")
names(facet.labs) <- sort(unique(mtcars$gear))
facet.labs
#>          3          4          5 
#> "very old"      "old"      "new"

mtcars |>
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(~factor(gear,
                     levels = names(facet.labs)[order(facet.labs, c(5,4,3))],
                     labels = facet.labs[order(facet.labs, c(5,4,3))]))

创建于2023-09-27带有reprex v2.0.2

原始答案

您可以在将齿轮传递给ggplot之前将其转换为因子,例如。

library(ggplot2)
facet.labs <- c("very old", "old", "new")
names(facet.labs) <- sort(unique(mtcars$gear))
facet.labs
#>          3          4          5 
#> "very old"      "old"      "new"

mtcars |> 
  dplyr::mutate(gear = factor(gear, levels = c(5, 4, 3))) |>
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(~gear, labeller = labeller(gear = facet.labs))

创建于2023-09-26带有reprex v2.0.2
这对你的用例有用吗?

相关问题