Strange, it does work directly on my computer. The error message suggests to me it could be a problem with the previous graph you plotted, have you tried dev.off() until you get back to the null device, then plotting again?
With R 4.0.0, caret_6.0-86, ggplot2_3.3.2, and lattice_0.20-41.
I closed RStudio and opened it again by running the script again and everything
solved.
What command should I put at the beginning of the script to initialize all the environment, Plot and console?
I know, separately
rm (list = ls ()) Empty Environment,
...? null device Plot
...? Ctr + L; Clear Console from keyboard
I don't feel this is necessary, personally I just use ctrl+shift+F10 to restart the R session regularly and rerun the script. Then I guess dev.off() would close any open graphical device, and you could imagine something like while(dev.cur()) dev.off(), but in practice buggy graphical devices are rare, and ctrl+shift+F10 will close them anyway.