To remove this error, use any one of the following ways:
Convert factor columns to numeric:
In the data frame below the year column needs to be converted to a numeric to get rid of this error:
df <- data.frame(year = c("1999", "2002", "2005", "2008"),
pollution = c(346.82,134.308821199349, 130.430379885892, 88.275457392443))
str(df)
'data.frame': 4 obs. of 2 variables:
$ year : Factor w/ 4 levels "1999","2002",..: 1 2 3 4
$ pollution: num 346.8 134.3 130.4 88.3
To convert to numeric:
df$year = as.numeric(as.character(df$year))
str(df)
'data.frame': 4 obs. of 2 variables:
$ year : num 1999 2002 2005 2008
$ pollution: num 346.8 134.3 130.4 88.3
Plotting the values:
ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = "Year", y = "Particulate matter emissions (tons)",title = "Motor vehicle emissions in Baltimore")
Output:
You can also add group = 1 into the ggplot or geom_line aes() because for line graphs, the data points must be grouped so that it knows which points to connect.i.e.,
ggplot(df, aes(year, pollution, group = 1)) + geom_point() + geom_line() + labs(x = "Year", y = "Particulate matter emissions (tons)", title = "Motor vehicle emissions in Baltimore")