Ggplot2 Dodge overlapping - keep the width of each element

Hope this will be easy to understand. This is 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 get Error in position_dodge(preserve = "single") : unused argument (preserve = "single"). ggplot2 version 2.2.1

So how to change the code

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

In order not to get this super wide bar, as shown below, but the same as there. enter image description here

+4
source share
1 answer

This argument was added position_dodgein the development version in January . This is not yet on CRAN.

A workaround would be to compute statistics outside of 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)

final schedule

This works because a zero counter is included in the data passed into the geometry.

+3
source

Source: https://habr.com/ru/post/1683875/


All Articles