【问题标题】:How do I create x-axis labels from two categorical variables in ggplot2?如何从 ggplot2 中的两个分类变量创建 x 轴标签?
【发布时间】:2021-03-02 07:36:15
【问题描述】:

我想在 ggplot2 中可视化以下数据集:

   WORD       CATEGORY             n  sum    gloss
   <fct>       <fct>           <int>  <int>  <fct>
 1 A            X                  4  4      'do'
 2 B            X                  3  3      'make'
 3 C            X                  6  9      'wash'
 4 C            Y                  3  9      'wash'    
 5 D            X                  2  2      'walk'
 6 E            X                  2  2      'sing'
 7 F            Y                  2  2      'dance'

我想在 y 轴上绘制 n 的值。在 x 轴上,我想绘制 WORD,但我也希望与每个单词相关联的 gloss 出现在单词值下方的一行上(即,好像有一个回车) .如何在 ggplot2 的 x 轴上绘制两个变量的信息?

【问题讨论】:

    标签: r dataframe ggplot2 plot data-visualization


    【解决方案1】:

    你也可以试试facet_wrap():

    library(ggplot2)
    library(dplyr)
    #Code
    df %>% mutate(gloss=factor(gloss,levels = unique(gloss),ordered = T)) %>%
      ggplot(aes(x=WORD,y=n,group=gloss))+
      geom_point()+
      facet_wrap(.~gloss,scales = 'free_x',nrow = 1,strip.position = 'bottom')+
      theme(strip.placement = 'outside',strip.background = element_blank())
    

    输出:

    或者使用interaction():

    #Code 2
    df %>% mutate(gloss=factor(gloss,levels = unique(gloss),ordered = T)) %>%
      ggplot(aes(x=interaction(WORD,gloss,sep = '\n'),y=n,group=gloss))+
      geom_point()+
      xlab('WORD')
    

    输出:

    使用的一些数据:

    #Data
    df <- structure(list(WORD = c("A", "B", "C", "C", "D", "E", "F"), CATEGORY = c("X", 
    "X", "X", "Y", "X", "X", "Y"), n = c(4L, 3L, 6L, 3L, 2L, 2L, 
    2L), sum = c(4L, 3L, 9L, 9L, 2L, 2L, 2L), gloss = c("'do'", "'make'", 
    "'wash'", "'wash'", "'walk'", "'sing'", "'dance'")), row.names = c(NA, 
    -7L), class = "data.frame")
    

    更新:此代码可以对数据进行排序:

    #Code 3
    df %>% mutate(gloss=factor(gloss,levels = unique(gloss),ordered = T)) %>%
      ggplot(aes(x=reorder(interaction(WORD,gloss,sep = '\n'),-n),y=n,group=gloss))+
      geom_point()+
      xlab('WORD')
    

    【讨论】:

    • 谢谢!我只有一个后续问题。根据n 或sum 的频率,我需要做什么代码才能让x 轴上的单词出现?
    • @Namenlos 我添加了更新。希望对你有帮助!
    • 非常感谢!
    【解决方案2】:

    您可以在scale_x_discrete() 的labels 参数中指定。我们只需要一个paste() 就可以将这些列组合在一起。

    ggplot(df) +
      geom_point(aes(x = WORD, y = n)) +
      scale_x_discrete(labels = paste(df$WORD, df$gloss, sep="\n"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多