I’ve been using ggplot for the most of data visualizations in R/RStudio.
It’s fantastic and absolutely love the package.
However, it always gives me troubles when saving the plots using ggsave() or export in Rstudio.
Fonts are always small when I’m trying to save them in 300dpi, or high resolution.
Saving images through Rstudio’s plots -> Export button always give blurr text/ or low-resolution figures if I tried to maintain bigger font size.
Are there any ways or more interactive way manipulating plot elements to get better quality figures, rather than making very long lines customizing font sizes in theme() section?
If there’s a package or routine you have been applying to get nice plots, I would like to know and
thanks for sharing!
7
It sounds like you’re spending time re-sizing many separate elements. With larger image dimensions and a larger default font size, the quality will be better. Please try using a complete theme function, including base_size = 15
(replacing 15 with various numbers) in the function parameters. For example, try adding
theme_minimal(base_size = 15) +
to your ggplot object. The default complete theme is theme_gray()
.
Your output will be more controlled if you export the image programmatically (technically speaking, by opening a ‘graphics device’). A common format to export to is .png (where you should load the png
package). Note that a LaTeX document can import PDF format with includegraphics{}
, and that maintains quality when zooming in. The PNG format is easier to export than the JPEG format. An example:
png(filename = "image_name.png",
width = 1200,
height = 800,
res = 190)
ggplot_object
dev.off()
Note that the res
argument is the resolution in ppi, so a higher number will make sizes smaller.
If you’re in VS Code, you can pull the image file to the right-hand side, to see the image file update in real-time. Otherwise, you can frequently use an image previewer (such as IrfanView) to preview your image as you update it.
Graphics Devices
The “Graphics_Devices_in_R” lesson in the “Exploratory_Data_Analysis” Swirl course gives an interactive introduction to what graphics devices are, so I encourage you to do that lesson if you are new to this. You can access it with
# install.packages("swirl")
library("swirl")
install_course("Exploratory_Data_Analysis")
swirl()
2