Stacked Bar Graph with Multiple Columns of Integers in R

409 Views Asked by At

Looking for some help with what I am assuming is a very simple task. From my data below, I want to create a stacked bar graph, with the fill = colnames(df_Consumers)[2,4]. I'm trying to get the x-axis to be df_Consumers$Month, the y-axis as df_Consumers$Referrals with the 2nd and 4th columns being the stacked bar graphs. I hope this makes sense. Apologies in advance if I am too vague. My ggplot code and data are below. Thanks in advance!

ggplot(df_Consumers, aes(x = Month, y = Referrals)) +
  geom_col(aes(fill = df_Consumers[2, 4]))

enter image description here

1

There are 1 best solutions below

4
On

ggplot likes long data frames. I'd suggest the following:

library(tidyverse)

df_Consumers %>%
  select(-Referrals) %>%
  pivot_longer(c(New.Consumers, No.Fill), names_to = "type", values_to = "value") %>%
  ggplot() + 
  aes(x = Month, y = value, fill = type) + 
  geom_col()