rggplot2line-plotrescale

ggplot two lines in one graph, error code?


I am pretty new to RStudio and try to plot two different lines in one graph. X-scale should be the year and the y-scale should be tons Carbon per hectar. Then I want to plot two lines for two different forest management types (BAUca and NATUREca). With the first 4 lines of the code I changed my data from factor to numeric.

mydata[] <- lapply(mydata, function(x) {
  if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(mydata, class)

ggplot(mydata, aes(x=Year, y=BAUca, group=1))+
  geom_line()+
  geom_line(y=NATUREca)

I get the following error code: Error in UseMethod("rescale") : no applicable method for 'rescale' applied to an object of class "factor"

As I said I already changed my data to numeric. So I am wondering why it stills give me this kind of error.

Here is a sample of my dataset:

Year    BAUca   NATUREca
2020    80.31   80.31
2025    83.43   92.76
2030    83.73   102.56
2035    84.76   112.72
2040    84.65   121.83
2045    84.84   131.38
2050    86.18   141.33

Would be very happy if someone has a solution for this error. Greetings, Frederic


Solution

  • You forgot to put y into aesthetic:

    mydata <- data.frame(
      Year = c(2020, 2025, 2030, 2035, 2040, 2045, 2050),
      BAUca = c(80.31, 83.43, 83.73, 84.76, 84.65, 84.84, 86.18),
      NATUREca = c(80.31, 92.76, 102.56, 112.72, 121.83, 131.38, 141.33)
    )
    
    ggplot(mydata, aes(x=Year, y=BAUca, group=1))+
      geom_line()+
      geom_line(aes(y=NATUREca))
    

    enter image description here