Search code examples
rggplot2graphlmloess

Geom_smooth line not showing up or not appearing on the graph in r


I am trying to graph a trend line to this graph(attached bellow). I have created a new dataframe (bothyearsdf) by combining two dataframes (df_year1 and df_year2). They had the same column names but different row values. I changed the class of the first column from "character" to "date" since it displays all the days in year 2019 and year 2020 (%y/%m/%d). I left the other column as it originally was, which was numeric.

      class(bothyearsdf$Data.first_max_value) #"numeric"
      class(bothyearsdf$Data.date_local) #"character"
      bothyearsdf$Data.date_local <- as.Date(df_year2$Data.date_local, 
      format='%y/%m/%d')
      class(bothyearsdf$Data.date_local)"date"

Then, I tried to use geom_smooth by itself- geom_smooth() -to create the line but it was giving me an error at first, "Error in FUN(X[[i]], ...) : object 'Data.date_local' not found." Then, I used the code bellow and it stopped giving me an error but it does not make a trend line on the plot. It also says "geom_smooth()` using method = 'loess' and formula 'y ~ x'"

Thank you in advance!!

picture of the graph

    w <- ggplot(NULL, aes(x=Data.date_local,y=Data.first_max_value)) +
         geom_point(data = bothyearsdf) + 
         geom_smooth(data = bothyearsdf, aes(x = Data.date_local,y = 
         Data.first_max_value, 
         color = 'red')) +
         labs(x = "Days", y = "PM2.5 Max Value", title = "Wake County, NC Max PM2.5 
         Value for 2019 and 2020")

     w

'''


Solution

  • What do you get if you try:

    w <- ggplot(bothyearsdf,
                aes(x = as.Date(Data.date_local),
                    y = Data.first_max_value)) +
      geom_point() + 
      geom_smooth(color = 'red') +
      labs(x = "Days", y = "PM2.5 Max Value",
      title = "Wake County, NC Max PM2.5 Value for 2019 and 2020")
    
    w