简体   繁体   中英

grouped bar plot with ggplot2 geom_bar is plotting proportions not counts

I'm trying to plot a grouped bar plot (x, y by another variable) but I'm getting a proportions graph (0-1) instead of counts, with all the bars going to 1. I'm confused because the code is seems correct (using stat identity and position dodge)

I've tried factoring the variables, doesn't work. The data frame is in long form.

ggplot(supra.long, aes(condition, measurement, fill = MODE)) +
  geom_bar(position = 'dodge', stat = "identity") 

Got the same result when I plotted this small portion of the data:

 A tibble: 6 x 3

condition measurement MODE 
  <chr>           <dbl> <chr>

INTACT              1 US   
INTACT              0 US   
INTACT              1 US   
FT                  0 MRI  
FT                  1 MRI  
FT                  0 MRI 

I'm expecting a plot of counts on the y axis, but the bars all go to 1 on a proportion scale.

I'd probably either summarise the data before I plot it and use the "identity" stat.

library(dplyr)
condition <- c("INTACT","INTACT","INTACT","FT","FT","FT")
measurement <- c(1,0,1,0,1,0)
MODE <- c("US","US","US","MRI","MRI","MRI")
supra.long <- data.frame(condition, measurement, MODE) %>%
  group_by(condition, MODE) %>%
  summarise(count = sum(measurement))

ggplot(supra.long) +
  geom_bar(aes(x=condition, y=count, fill = MODE), position = 'dodge', stat = "identity") 

Or I would filter out the zeros and use the "count" stat.

supra.long <- data.frame(condition, measurement, MODE) %>% filter(measurement > 0)
ggplot(supra.long) +
  geom_bar(aes(x=condition,fill = MODE), position = 'dodge', stat = "count") 

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM