【问题标题】:Manually label axis in ggplot when using facet_wrap()使用 facet_wrap() 时在 ggplot 中手动标记轴
【发布时间】:2021-03-07 19:23:53
【问题描述】:

我正在尝试手动标记我的 x 轴,但是当我刻面我的图并释放我的 x 轴的比例时,标签变得不正确。我想知道是否有办法防止这种情况发生,而不必事先手动更改我的字符串。

当我使用 scale_x_discrete() 手动标记 x 轴时,标签是正确的

library(tidyverse)

df <- data.frame(trial = rep(c("a", "b", "c"), each = 30),
                 values = rnorm(n = 90, mean = 0, sd = 1),
                 variable = c(rep("n", times = 60), rep("m", times = 30))
                 )

df %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  scale_x_discrete(labels = c("A", "B", "C")) +
  theme(legend.position = "none") 

Plot 1

但是,当我处理我的情节时,标签变得不正确。

df %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  scale_x_discrete(labels = c("A", "B", "C")) +
  facet_wrap(~ variable, scales = "free_x") +
  theme(legend.position = "none")

Plot 2

【问题讨论】:

    标签: r ggplot2 tidyverse tidyr facet


    【解决方案1】:

    试试这个:

    library(ggplot2)
    library(dplyr)
    #Code
    df %>%
      ggplot(aes(x = trial, y = values)) +
      geom_violin(aes(fill = trial)) +
      scale_x_discrete(breaks=c('a','b','c'),labels = c("A", "B", "C")) +
      facet_wrap(~ variable, scales = "free_x") +
      theme(legend.position = "none")
    

    输出:

    或者您也可以尝试使用mutate() 格式化变量:

    #Code 2
    df %>%
      mutate(trial=factor(trial,levels = unique(trial),labels = c("A", "B", "C"))) %>%
      ggplot(aes(x = trial, y = values)) +
      geom_violin(aes(fill = trial)) +
      facet_wrap(~ variable, scales = "free_x") +
      theme(legend.position = "none")
    

    相同的输出。或者听从 @cookesd 的建议(非常感谢并感谢他):

    #Code 3
    df %>%
      ggplot(aes(x = trial, y = values)) +
      geom_violin(aes(fill = trial)) +
      scale_x_discrete(labels = c('a' = 'A', 'b' = 'B', 'c' = 'C')) +
      facet_wrap(~ variable, scales = "free_x") +
      theme(legend.position = "none")
    

    同样的输出。

    【讨论】:

    • 或者您可以像这样将命名列表传递给标签参数scale_x_discrete(labels = c('a' = 'A', 'b' = 'B', 'c' = 'C')
    • @cookesd 很棒的建议,我会为你更新!
    【解决方案2】:

    我们可以从forcats使用fct_recode

    library(forcats)
    library(dplyr)
    library(ggplot2)
    df %>% 
       mutate(trial = fct_recode(trial, A= 'a', B = 'b', C = 'c'))  %>% 
      ggplot(aes(x = trial, y = values)) + 
           geom_violin(aes(fill = trial)) +
           facet_wrap(~ variable, scales = "free_x") + 
           theme(legend.position = "none")
    

    -输出

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多