-2

I have two columns in a data.frame. lets say one is called "before" and the other is "after". each of these 2 factors has 5 levels (very satisfied, satisfied, somehow, dissatisfied, very dissatisfied).

This is the data:

dat <- structure(list(before = structure(c(2L, 5L, 5L, 1L, 3L, 3L), .Label = c("very satisfied", 
"satisfied", "somehow", "dissatisfied", "very dissatisfied"), class = "factor"), 
    after = structure(c(3L, 3L, 5L, 2L, 2L, 2L), .Label = c("very satisfied", 
    "satisfied", "somehow", "dissatisfied", "very dissatisfied"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

How to build a side by side by plot so that for each of those 5 levels, there are 2 bars (before and after) side by side represented?

Paul
  • 2,877
  • 1
  • 12
  • 28
  • You have to restructure your data to long format. In ggplot2, data structure required for plotting is not like excel. – AnilGoyal Mar 03 '21 at 01:07
  • Does this answer your question? [side-by-side barplot with ggplot](https://stackoverflow.com/questions/42084775/side-by-side-barplot-with-ggplot) – AnilGoyal Mar 03 '21 at 01:10

2 Answers2

0

After pivoting your data, you can use position = "dodge" to get your groups side-by-side.

dat %>%
  pivot_longer(everything(), names_to = "period", values_to = "score") %>%
  ggplot(aes(x = score, group = period, fill = period)) +
  geom_bar(position = "dodge")
Paul
  • 2,877
  • 1
  • 12
  • 28
0
library(tidyverse)

dat %>% pivot_longer(cols = 1:2) %>%
  ggplot() +
  geom_bar(aes(value, color = name), position = "dodge", fill = "grey")

enter image description here

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45