displaying columns side by side for a variable in R

Viewed 28

How can I show the three values of "disp" for a particular cylinder? Only one column is getting displayed. I am expecting three columns for each cylinder. Any suggestions?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)
mtcars %>% arrange(desc(disp)) %>% group_by(cyl) %>% slice_head(n = 3) %>% 
  ggplot(aes(cyl, disp)) + geom_col() +facet_wrap(. ~ cyl)

Created on 2022-06-27 by the reprex package (v2.0.1)

1 Answers

Use Position_dodge or Position_dodge2

mtcars |> arrange(desc(disp)) |> group_by(cyl) |> slice_head(n = 3) |> 
  ggplot(aes(cyl, disp)) + geom_col(aes(fill = disp), position = position_dodge2())

Then you can fill in the bars with whatever variable.

enter image description here

Related