ggplot到png - 自动拉伸图像

Shi*_*dra 1 png r image ggplot2

我正在生成一个ggplot plot并将其保存为.png图像.虽然在Rstudio中生成的绘图根据y轴的值拉伸,但是当我将其保存为时,我得到一个方形图像.png.

如何在.png表格中自动获得最佳拉伸图像?

# 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)
Run Code Online (Sandbox Code Playgroud)

Pau*_*tra 9

为了节省ggplot数字,我会用ggsave.默认情况下,这会获取绘图设备的大小.因此,如果您在屏幕上的绘图设备中设置正确的宽高比,则会转换为已保存的图像文件.此外,它支持设置的宽度,高度,和图像的经由DPI width,heightdpi输入参数.

例如:

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)
Run Code Online (Sandbox Code Playgroud)

  • `ggsave` 不是一个单独的包,而是 `ggplot2` 中的一个函数。 (2认同)
  • 根据绘图自动选择正确的纵横比并不是很简单,而且也非常依赖于您的特定数据类型。据我所知,没有任何函数可以做到这一点。不过,您可以尝试自己想出一些办法。 (2认同)