Search code examples
rggplot2graphbar-chartdata-analysis

Grouped bar chart time series in R?


I have a csv file in the format shown below.

enter image description here

I would like to plot a grouped bar chart, where the four values (one for each of the four columns like great_deal, only_some, etc) for a given year are grouped next to each other in a time series. However, when I run the code below, it displays a "stacked" and not grouped bar chart. Does anyone know how I might write the correct code for such a grouped bar chart using ggplot2?

ggplot(confinan)+
  geom_bar(mapping=aes(x=year, y=great_deal, fill="blue"), stat="identity", position="dodge")+
  geom_bar(mapping=aes(x=year, y=dont_know, fill="red"), stat="identity", position="dodge")

Solution

  • I was able to get your desired chart by doing a pivot_longer() thrown in before the ggplot like so

    confinan %>% select(everything()) %>%
        pivot_longer(.,
            cols=c(great_deal,only_some,hardly_any,dont_know),
            names_to="Var",
            values_to="Val") %>%
        ggplot(aes(y=Val,x=year,fill=Var))+
        geom_bar(stat="identity", position="dodge")