0

I am simply trying to produce a bar plot (with ggplot) where both plan_preg and plan_wanted are on the same graph (as two separate groups) representing their counts of yes and no's.

df <- structure (list(subject_id = c("191-5467", "191-6784", "191-3457", "191-0987", "191-1245", 
                                     "191-2365", "191-4532", "191-9901", "191-2710"), 
                      plan_preg = c("Yes","No","No","No","Yes","No", "NA", "Yes", "Yes"),
                      plan_wanted = c("Yes","No","Yes","Yes","NA","No","NA", "Yes", "No")), 
                 class = "data.frame", row.names = c (NA, -9L))

What I've tried:

df_long <- tidyr::pivot_longer(df, cols=-1)
ggplot(preg_long, aes(x = name, y = factor(value), fill = name)) + # specify x and y axis, specify fill
  geom_col(position = position_dodge(0.7), width = 0.6, color = "black") + # position.dodge sets the bars side by side
  theme_minimal()

enter image description here

Thandi
  • 225
  • 1
  • 2
  • 9
  • What did you try? What didn't work? Possibly helpful: https://stackoverflow.com/questions/67233995/barplot-for-count-data-with-multiple-columns – MrFlick Feb 21 '23 at 20:18
  • In the referenced question they grouped by sex, I do not want a grouping variable. I need one x axis with two bars (yes/no) for plan_preg and another two bars for plan_wanted. I know how to plot two separate plots but struggling with this one – Thandi Feb 21 '23 at 20:27
  • 2
    You have to reshape your data, see e.g. https://stackoverflow.com/questions/64803503/stacked-bar-ggplot2-in-r or https://stackoverflow.com/questions/71875064/how-to-create-a-ggplot-bar-chart-with-multiple-columns-of-data-for-y or https://stackoverflow.com/questions/75211760/bar-plot-in-ggplot2 – stefan Feb 21 '23 at 20:34
  • How would I edit this if the y axis is not values but rather count of factor variables? It's currently not counting – Thandi Feb 21 '23 at 21:03
  • Try `ggplot(preg_long, aes(x = name, fill = value)) + geom_bar(position = position_dodge(0.7), ...)` – stefan Feb 21 '23 at 21:29
  • I get this error "Error in `check_required_aesthetics()`: ! geom_col requires the following missing aesthetics: y Run `rlang::last_error()` to see where the error occurred." – Thandi Feb 21 '23 at 21:55
  • 1
    Use `geom_bar` not `geom_col`. – stefan Feb 22 '23 at 00:27

0 Answers0