How to Fix the Error: Mapping Must be Created by aes() in GGPLOT2
“Error: mapping must be created by aes()” is an error you would eventually run into if you frequently use GGPLOT2 to create graphs in R. The last time I ran into this error was when I was creating profile plots using geom_line(). I succeeded to recreate the error using the R codes below.
Visit this page if you would like to understand the dataset used in this post. We will immediately go into fixing the error. I was able to fix the error with any one of the following four methods:
1. Place the aes() and data= arguments in the ggplot call
Place the aes() and data= arguments in the ggplot() instead of the geom_() function.
#try doing this:
ggplot(statsBG, aes(x=timedays, y=meanBG, color=groupid)) +
geom_line()
#instead of this:
ggplot() +
geom_line(statsBG, aes(x=timedays, y=meanBG, color=groupid))
2. Use the mapping= syntax
Try using the mapping= syntax as shown below
#use the mapping= syntax
ggplot() +
geom_line(statsBG, mapping=aes(x=timedays, y=meanBG, color=groupid))
C. Use the data= syntax
Try using the data= syntax for the dataset argument.
#use the data= syntax
ggplot() +
geom_line(data=statsBG, aes(x=timedays, y=meanBG, color=groupid))
D. Specify aes() first
#specify aes() first before the dataset argument
ggplot() +
geom_line(aes(x=timedays, y=meanBG, color=groupid), statsBG)
We hope you were able to fix your error with one of the above methods. If you have any tips or comments, please leave them in the comment field below.