JuanTamad
JuanTamad

Reputation: 65

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.

Upvotes: 0

Views: 1376

Answers (1)

olorcain
olorcain

Reputation: 1248

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.

Upvotes: 0

Related Questions