One error you may encounter in R is:
Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state
This error may occur for three reasons:
1. You are creating plots in both base R and ggplot2 in the same session.
2. Your version of ggplot2 is not compatible with your version of R.
3. Your graphics settings are preventing new plots from being created.
This tutorial shares three methods you can use to resolve this error.
How to Reproduce the Error
Suppose we attempt to create a scatterplot using the built-in mtcars dataset in R:
library(ggplot2) #attempt to create scatterplot ggplot(mtcars, aes(x=mpg, y=hp)) + geom_point()
We receive the invalid graphics state error, but it’s not clear why.
The following three methods show how to troubleshoot this error.
Method #1: Fix the Error by Using dev.off()
The first method you should try (and the easiest method) is to simply use dev.off() to shut down the current plotting device.
You can then run your original code again to create the scatterplot.
In many cases, this can fix the error because it removes any plot settings that were used for previous plots that may be interfering with your current plot.
Method #2: Fix the Error by Restarting RStudio
If the previous method didn’t work, you can try restarting your RStudio session.
In many cases, this can also fix the error because it clears out any previous plot settings that were interfering with your current plot.
Method #3: Fix the Error by Reinstalling ggplot2
If the previous two methods didn’t work, you may need to uninstall and then reinstall ggplot2.
You can use the following syntax to uninstall your current version of ggplot2:
#uninstall ggplot2 remove.packages("ggplot2")
You can then use the following syntax to install the latest version of ggplot2:
#install ggplot2 install.packages("ggplot2")
You can then run the code again to create the scatterplot:
In most cases, we will now be able to create the plot without any errors.
The following tutorials explain how to fix other common problems in R: