One error you may encounter in R is:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a numeric vector
This error occurs when you attempt to use ggplot2 to plot variables in a data frame, but you reference a vector instead of a data frame for the data argument.
This tutorial shares exactly how to fix this error.
How to Reproduce the Error
Suppose we have the following data frame in R:
#create data frame
df <- data.frame(x=c(1, 2, 3, 4, 5, 6, 7, 8),
y=c(4, 8, 14, 19, 14, 13, 9, 9))
#view data frame
df
x y
1 1 4
2 2 8
3 3 14
4 4 19
5 5 14
6 6 13
7 7 9
8 8 9
Now suppose we attempt to create a scatter plot to visualize the x and y variables within the data frame:
library(ggplot2)
#attempt to create scatter plot
ggplot(df$x, aes(x=x, y=y)) +
geom_point()
Error: `data` must be a data frame, or other object coercible by `fortify()`,
not a numeric vector
We receive an error because we referenced a numeric vector (df$x) within the data argument of the ggplot() function instead of a data frame.
How to Fix the Error
The way to fix this error is to reference a data frame for the data argument within the ggplot() function.
In our example, we should use df instead of df$x for the data argument:
library(ggplot2)
#create scatter plot
ggplot(df, aes(x=x, y=y)) +
geom_point()
Notice that we’re able to create the scatter plot successfully without any error this time.
Additional Resources
The following tutorials explain how to troubleshoot other common errors in R:
How to Fix: ggplot2 doesn’t know how to deal with data of class uneval
How to Fix: Error in stripchart.default(x1, …) : invalid plotting method
How to Fix: Error in eval(predvars, data, env) : object ‘x’ not found