代码之家  ›  专栏  ›  技术社区  ›  MadelineJC

group_by在R中按顺序排列数字

  •  0
  • MadelineJC  · 技术社区  · 2 年前

    我试图制作一个堆叠的直方图,但遇到了分组/排序数据的问题,我无法解决。例如,当我对数据进行分组时,输出表示100<90(我认为是因为1<9),我不知道如何使用整数将R分组。

    举个例子:

    library(tidyverse)
    
    # Fake data
    Sims <- seq(1,100,1)
    CoOc <- sample(90:140, 100, replace = TRUE)
    Out <- sample(c("A Wins", "B Wins", "Tie"), 100, replace = TRUE)
    df <- data.frame(cbind(Sims, CoOc, Out))
    
    # Ordering data for stacked histogram
    df2 <- df %>% 
      group_by(CoOc, Out) %>% # Grouping by CoOc for the x-axis ordering, and then for Out to get outcome (A Wins, B Wins, Tie) grouped together
      summarize(Counts = n())
    
    # Plotting
    ggplot(df2)+ 
      geom_bar(aes(fill = Out, y = Counts, x = CoOc), 
               position = "stack", stat = "identity")+
      labs(title="Example",
           x="CoOc",
           y="Num")+
      scale_fill_manual(name = "Outcome",
                        values = c("#AD1457", "#B3E5FC", "#FF9800"))+
      theme_bw()+ 
      theme(panel.border = element_blank(), 
            panel.grid.major = element_blank(), 
            panel.grid.minor = element_blank(), 
            axis.line = element_line(colour = "white"), 
            plot.caption.position = "plot", 
            plot.caption = element_text(hjust = 0))
    

    这给了我一个这样的图(注意x轴最初上升,但随后下降到一个较低的数字): enter image description here

    非常感谢您的帮助,如果这是一个愚蠢的问题,我很抱歉!

    1 回复  |  直到 2 年前
        1
  •  2
  •   Deepansh Arora    2 年前

    使用ggplot2命令时,只需将“CoOc”转换为数字(x=as.numeric(CoOc)),然后进行绘图。

    library(tidyverse)
    
    # Fake data
    Sims <- seq(1,100,1)
    CoOc <- sample(90:140, 100, replace = TRUE)
    Out <- sample(c("A Wins", "B Wins", "Tie"), 100, replace = TRUE)
    df <- data.frame(cbind(Sims, CoOc, Out))
    
    # Ordering data for stacked histogram
    df2 <- df %>% 
      group_by(CoOc, Out) %>% # Grouping by CoOc for the x-axis ordering, and then for Out to get outcome (A Wins, B Wins, Tie) grouped together
      summarize(Counts = n()) 
    
    # Plotting
    ggplot(df2)+ 
      geom_bar(aes(fill = Out, y = Counts, x = as.numeric(CoOc)), 
               position = "stack", stat = "identity")+
      labs(title="Example",
           x="CoOc",
           y="Num")+
      scale_fill_manual(name = "Outcome",
                        values = c("#AD1457", "#B3E5FC", "#FF9800"))+
      theme_bw()+ 
      theme(panel.border = element_blank(), 
            panel.grid.major = element_blank(), 
            panel.grid.minor = element_blank(), 
            axis.line = element_line(colour = "white"), 
            plot.caption.position = "plot", 
            plot.caption = element_text(hjust = 0))
    
    

    enter image description here