Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 Dodge overlapping - preserve the width of each element

Tags:

r

ggplot2

Hope it will be easy to understand. It's basically the same example as here.

enter image description here

Using

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
   geom_bar(position = position_dodge(preserve = "single"))

But I'm getting Error in position_dodge(preserve = "single") : unused argument (preserve = "single")/. ggplot2 version 2.2.1

So how to modify code

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
     geom_bar(position = "dodge")

To not get this super wide bar like below but same as there. enter image description here

like image 226
AlienDeg Avatar asked Aug 17 '17 07:08

AlienDeg


1 Answers

That argument was added to position_dodge in the development version in january. It's not yet on CRAN.

A workaround would be to calculate the statistics outside ggplot2:

ggplot(as.data.frame(with(mtcars, table(cyl = factor(cyl), vs = factor(vs)))), 
       aes(factor(cyl), y = Freq, fill = factor(vs))) +
  geom_col(position = "dodge") + 
  scale_fill_discrete(drop = FALSE)

resulting plot

This works because the zero count is included in the data passed to the geom.

like image 96
Roland Avatar answered Nov 02 '22 13:11

Roland