ggplot to png - automatically stretching image

2019-05-29 21:12发布

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)

1条回答
唯我独甜
2楼-- · 2019-05-29 21:33

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)
查看更多
登录 后发表回答