One error you may encounter in R is:
Error in ggplot(df, aes(x = x, y = y)) : could not find function "ggplot"
This error occurs when you attempt to create a plot using the ggplot2 data visualization package, but have failed to load the package first.
This tutorial explains five potential ways to fix this error.
How to Reproduce this Error
Suppose we run the following code in R:
#create data frame df frame(x=c(1, 2, 4, 5, 7, 8, 9, 10), y=c(12, 17, 27, 39, 50, 57, 66, 80)) #create scatterplot of x vs. y ggplot(df, aes(x=x, y=y)) + geom_point() Error in ggplot(df, aes(x = x, y = y)) : could not find function "ggplot"
We receive an error because we haven’t loaded the ggplot2 package in our current R environment.
Potential Fix #1: Load the ggplot2 Package
The most common way to fix this error is to simply load the ggplot2 package using the library() function:
library(ggplot2) #create scatterplot of x vs. y ggplot(df, aes(x=x, y=y)) + geom_point()
In many cases, this will fix the error.
Potential Fix #2: Install ggplot2
If fix #1 doesn’t work, you may need to install ggplot2 using the install.packages() function:
#install ggplot2 install.packages("ggplot2") #load ggplot2 library(ggplot2) #create scatterplot of x vs. y ggplot(df, aes(x=x, y=y)) + geom_point()
Potential Fix #3: Install ggplot2 with Dependencies
If the previous fixes don’t work, you may need to install ggplot2 and also specify to install any packages that ggplot2 depends on:
#install ggplot2 and all dependencies install.packages("ggplot2", dependencies=TRUE) #load ggplot2 library(ggplot2) #create scatterplot of x vs. y ggplot(df, aes(x=x, y=y)) + geom_point()
Potential Fix #4: Remove & Re-Install ggplot2
If the previous fixes don’t work, you may need to remove the current version of ggplot2 completely and re-install it:
#remove ggplot2 remove.packages("ggplot2") #install ggplot2 install.packages("ggplot2") #load ggplot2 library(ggplot2) #create scatterplot of x vs. y ggplot(df, aes(x=x, y=y)) + geom_point()
Potential Fix #5: Run the Correct Code Chunk
If none of the previous fixes work, you may need to simply verify that you’re running the correct code chunk in R that actually installs and loads the ggplot2 package.
In many circumstances, you may simply forget to run both lines that install and load ggplot2 in R.
Additional Resources
The following tutorials explain how to fix other common errors in R:
How to Fix in R: Cannot use `+.gg()` with a single argument
How to Fix in R: incorrect number of subscripts on matrix
How to Fix in R: Subscript out of bounds