【问题标题】:Change factor label ggplot when scale_x_reordered() is present存在 scale_x_reordered() 时更改因子标签 ggplot
【发布时间】:2021-08-22 02:37:46
【问题描述】:

我正在创建一个箱线图,其中我在调整 x 轴上的因子顺序后使用了 scale_x_reordered()。

我现在正在尝试更改一个因素的标签。我以前一直在使用:

scale_x_discrete(labels=c("old_label" = "new_label"))

但是,我不能在同一个图中同时使用 scale_x_discrete() 和 scale_x_reordered() 。有谁知道修复,以便我可以更改标签并保持 scale_x_reordered?

我的 ggplot 基于这个非常有用的示例:linked here

我正在尝试进行的更改相当于手动将名称“Michael”更改为“Mike”。

【问题讨论】:

  • 尝试将labels=c("old_label" = "new_label") 作为scale_x_reordered 的参数
  • 是的,我试过了。我收到错误消息:“discrete_scale 中的错误(c(“x”,“xmin”,“xmax”,“xend”),“position_d”,:由多个实际参数匹配的形式参数“标签””
  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example

标签: r ggplot2 axis-labels


【解决方案1】:

为了达到您想要的结果,我建议在申请 reorder_within 之前重新编码您的因素。

原因是reorder_within 转换因子水平以使构面内的重新排序起作用。在scale_x_reordered 内部,通过labels 参数应用重新转换以显示原始级别或标签。这就是你不能使用labels 参数的原因。

以下示例取自您发布的链接,我在reorder_within 之前使用了dplyr::recode(name, "Michael" = "Mike")

library(tidyverse)
library(babynames)
library(tidytext)

top_names <- babynames %>%
  filter(year >= 1950,
         year < 1990) %>%
  mutate(decade = (year %/% 10) * 10) %>%
  group_by(decade) %>%
  count(name, wt = n, sort = TRUE) %>%
  ungroup

top_names %>%
  group_by(decade) %>%
  top_n(15) %>%
  ungroup %>%
  mutate(decade = as.factor(decade),
         name = recode(name, "Michael" = "Mike"),
         name = reorder_within(name, n, decade)) %>%
  ggplot(aes(name, n, fill = decade)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~decade, scales = "free_y") +
  coord_flip() +
  scale_x_reordered() +
  scale_y_continuous(expand = c(0,0)) +
  labs(y = "Number of babies per decade",
       x = NULL,
       title = "What were the most common baby names in each decade?",
       subtitle = "Via US Social Security Administration")
#> Selecting by n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 2014-08-16
    • 2022-11-23
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多