【问题标题】:ggplot to png - automatically stretching imageggplot to png - 自动拉伸图像
【发布时间】:2017-03-20 14:24:13
【问题描述】:

我正在生成一个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)

【问题讨论】:

    标签: r image ggplot2 png


    【解决方案1】:

    为了保存ggplot 数字,我会使用ggsave。默认情况下,这会获取绘图设备的大小。因此,如果您在屏幕上的绘图设备中正确设置纵横比,这将转换为保存的图像文件。此外,它还支持通过widthheightdpi输入参数设置图像的宽度、高度和dpi。

    例如:

    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)
    

    【讨论】:

    • 一般来说这是一个更好的选择。但我被困在不支持ggsave 的服务器上的旧版本 R(没有安装权限)上。我收到此错误消息package ‘ggsave’ is not available (for R version 3.3.1) 另外,我不想手动指定尺寸。它应该根据美学选择尺寸。
    • ggsave 不是单独的包,而是ggplot2 中的一个函数。
    • 并且根据绘图自动选择正确的纵横比并不是很简单,而且还非常依赖于您的特定数据类型。据我所知,没有任何功能可以做到这一点。但是,您可以尝试自己想出一些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2014-10-20
    相关资源
    最近更新 更多