Shivendra Shivendra - 29 days ago 7
R Question

ggplot to png - automatically stretching image

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)

Answer

For saving ggplot figures, I would use ggsave. 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 the width, height and dpi input arguments.

For example:

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")
# ggsave will save the last generated image, it will also pick up which file format
# to use from the file extension (e.g. png).
ggsave('~/saved_image.png', width = 16, height = 9, dpi = 100)