0

I want to plot percent survival per treatment (percent.o2). When y == 0% for a treatment, I get a fat bar. I'd like them to be the same width. Any advice appreciated.

Data looks like this:

> plotData
# A tibble: 12 x 4
# Groups:   Percent.O2 [7]
   Status        Percent.O2     n percent
   <fct>         <fct>      <int>   <dbl>
 1 Dead          1            144  1.00  
 2 Dead          3            141  0.979 
 3 Dead          7            144  1.00  
 4 Dead          10           105  0.729 
 5 Dead          13            69  0.958 
 6 Dead          Control       12  0.167 
 7 Dead          Control2       2  0.0278
 8 Still_kicking 3              3  0.0208
 9 Still_kicking 10            39  0.271 
10 Still_kicking 13             3  0.0417
11 Still_kicking Control       60  0.833 
12 Still_kicking Control2      70  0.972 

Here's my code for the plot:

> ggplot(plotData, aes(x = Percent.O2, y = percent, fill = Status)) + geom_col(position = "dodge")

enter image description here

user974887
  • 2,309
  • 3
  • 17
  • 18
  • this might help: https://stackoverflow.com/questions/10834382/ggplot2-keep-unused-levels-barplot – MLavoie Feb 09 '18 at 20:17
  • I added drop = FALSE and I get the same result. – user974887 Feb 09 '18 at 20:22
  • ggplot(plotData, aes(x = Percent.O2, y = percent, fill = Status)) + geom_col(position = "dodge") + scale_fill_discrete(drop = FALSE) + scale_x_discrete(drop = FALSE) Produces the same chart – user974887 Feb 09 '18 at 20:23

1 Answers1

1

You can use the complete function from the tidyr package (which is loaded as part of the tidyverse suite of packages) to add rows for the missing levels and fill them with zero (NA, the default fill value, would work too). I've also added percent labels on the y-axis using percent from the scales package.

library(tidyverse)
library(scales)

ggplot(plotData %>% 
         complete(Status, nesting(Percent.O2), fill=list(n=0, percent=0)), 
       aes(x = Percent.O2, y = percent, fill = Status)) + 
  geom_col(position = "dodge") +
  scale_y_continuous(labels=percent)

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285