Issue with ggplot2, geom_bar, and position=“dodge”: stacked has correct y values, dodged does not

后端 未结 1 605
野趣味
野趣味 2020-12-01 08:23

I\'m having quite the time understanding geom_bar() and position=\"dodge\". I was trying to make some bar graphs illustrating two groups. Originall

1条回答
  •  有刺的猬
    2020-12-01 08:46

    I think the problem is that you want to stack within values of the num group, and dodge between values of num. It might help to look at what happens when you add an outline to the bars.

    library(ggplot2)
    set.seed(123)
    df <- data.frame(
      id     = 1:18,
      names  = rep(LETTERS[1:3], 6),
      num    = c(rep(1, 15), rep(2, 3)),
      values = sample(1:10, 18, replace=TRUE)
    )
    

    By default, there are a lot of bars stacked - you just don't see that they're separate unless you have an outline:

    # Stacked bars
    ggplot(df, aes(x=factor(names), y=values, fill=factor(num))) + 
      geom_bar(stat="identity", colour="black")
    

    Stacked bars

    If you dodge, you get bars that are dodged between values of num, but there may be multiple bars within each value of num:

    # Dodged on 'num', but some overplotted bars
    ggplot(df, aes(x=factor(names), y=values, fill=factor(num))) + 
      geom_bar(stat="identity", colour="black", position="dodge", alpha=0.1)
    

    Dodged on num

    If you also add id as a grouping var, it'll dodge all of them:

    # Dodging with unique 'id' as the grouping var
    ggplot(df, aes(x=factor(names), y=values, fill=factor(num), group=factor(id))) + 
      geom_bar(stat="identity", colour="black", position="dodge", alpha=0.1)
    

    Dodge all bars

    I think what you want is to both dodge and stack, but you can't do both. So the best thing is to summarize the data yourself.

    library(plyr)
    df2 <- ddply(df, c("names", "num"), summarise, values = sum(values))
    
    ggplot(df2, aes(x=factor(names), y=values, fill=factor(num))) + 
      geom_bar(stat="identity", colour="black", position="dodge")
    

    Summarized beforehand

    0 讨论(0)
提交回复
热议问题