Home > front end >  GGplot columns don't exist
GGplot columns don't exist

Time:11-18

I'm VERY new to R and I am trying to make a stacking bar plot with each bar corresponding to a different year. Year will be the x axis while Frequency is on the y axis. I keep getting an error saying that "columns 2014,2015, ect dont exist". I don't quite understand where I went wrong. I have attached a picture of what I'd like it to look like, it's just an example so the numbers in the picture are arbitrary. Thanks

enter image description here

library(dplyr)
library(tidyr)
library(ggplot2)
data <- data.frame(
  Emm1.0 = c(5,2,0,0,0,0,2,0), 
  Emm3.1 = c(1,1,0,0,0,0,0,0), 
  Emm6.4 = c(1,0,0,0,0,0,0,0),
  Emm9.0 = c(0,0,0,0,0,0,0,1),
  Emm11.0 = c(0,2,4,3,0,0,0,0),
  Emm22.0 = c(1,0,0,0,0,1,0,0),
  Emm28.0 = c(0,0,0,0,0,1,0,0),
  Emm41.1 = c(1,0,1,0,0,0,0,0),
  Emm49.0 = c(2,0,0,0,0,2,4,8),
  Emm53.0 = c(0,0,0,0,1,0,0,0),
  Emm59.0 = c(0,1,1,3,0,0,0,1),
  Emm74.0 = c(2,0,0,0,1,2,1,2),
  Emm76.0 = c(2,0,0,0,1,1,1,1),
  Emm77.0 = c(0,0,0,0,0,0,1,1),
  Emm81.0 = c(1,0,0,0,1,3,3,0),
  Emm82.0 = c(1,0,0,0,0,0,1,0),
  Emm83.1 = c(0,0,1,0,0,1,0,0),
  Emm87.0 = c(0,1,0,0,0,0,0,0),
  Emm89.0 = c(0,0,1,0,1,0,0,0),
  Emm91.0 = c(0,0,0,0,1,0,0,0),
  Emm101.0 = c(1,0,1,0,0,0,0,0),
  Emm114.0 = c(0,0,0,1,0,0,0,0),
  Emm118.0 = c(1,0,0,0,0,0,0,0),
  Year = as.factor(c("2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021"))

data <- dat %>%
  gather("Emmtype", "Frequency", -Year)

data
ggplot(data, aes(x = Year, y = Frequency, fill = Emmtype))   
  geom_col(position = "stack", stat = "identity")

CodePudding user response:

Maybe you want something like this: When you use geom_col() you don't need stat = "identity" (see ?geom_bar(), you already have an y:

library(tidyverse)
data %>% 
  pivot_longer(-Year) %>% 
  ggplot(aes(x = Year, y = value, fill = name))   
    geom_col(position = "stack")

enter image description here

  • Related