I am generating a ggplot plot
and saving it as .png
image. While the plot generated in Rstudio stretches according to the values in y-axis, I get a square looking image when I save it as .png
.
How to get the best stretched image automatically in .png
form?
# Function to store ggplot plot object as .png image file
savePlot <- function(myPlot, filename) {
png(filename)
print(myPlot)
dev.off()
}
# ggplot object
normalized_bar_plot = ggplot(dat, aes(factor(temp), norm, fill = type)) +
geom_bar(stat="identity", position = "dodge") + ylab("Normalized count")+xlab(features[i])+
scale_fill_brewer(palette = "Set1")
filename = paste0("image_", features[i], ".png")
savePlot(normalized_bar_plot, filename)
For saving
ggplot
figures, I would useggsave
. By default this picks up the size of the plot device. So if you set your aspect ratio correct in the plot device on screen, this will translate to the saved image file. In addition, it supports setting the width, height, and dpi of the image via thewidth
,height
anddpi
input arguments.For example: