Home > database >  ggplot issues. Line chart not populating
ggplot issues. Line chart not populating

Time:06-03

Here is the sample data. as currently constructed, am getting nothing displayed. the end goal is to have a line chart that displays from left to right with the various indcodes. What am I missing in order to have three lines representing the avgemp values for each indcode?

 library(dplyr)
 library(ggplot2)

 date1 <- c("2002-01-01","2002-02-01","2002-03-01","2002-01-01","2002-02-01","2002-03-01","2002-01-01","2002-02-01","2002-03-01")
 indcode <- c(7113,7113,7113,7112,7112,7112,7131,7131,7131)
 avgemp <- c(100,101,102,90,92,98,244,210,585)

 test1 <- data.frame(date1,indcode,avgemp)

 test1chart<- test1 %>% group_by(indcode) %>% ggplot(aes(x = date1, y = indcode))

 test1chart

CodePudding user response:

You've got a few issues:

  • group_by is for dplyr, it does nothing for ggplot
  • name mismatch: your data has column date1, your plot code uses x = date
  • What goes on the y-axis? If you want a line for each indcode, then probably y = avgemp, not indcode
  • Tell ggplot what points to connect (this is the "group" aesthetic) aes(group = indcode)
test1 %>%
  ggplot(aes(x = date1, y = avgemp, group = indcode))  
  geom_line()

enter image description here

Other changes you may want to make:

  • Want to tell the lines apart? Maybe by color? Put color = factor(indcode) inside the aes()

  • Have a lot of data and don't want to label every single date? Or maybe your dates are irregularly spaced? Stop treating your date1 column as categorical by converting it to Date class: test1 <- test1 %>% mutate(date1 = as.Date(date1)

  • Related