2016-11-07 73 views
0

我正在生成ggplot plot并将其保存为.png图像。虽然在Rstudio中生成的绘图根据y轴上的值延伸,但当我将其保存为.png时,我会看到方形图像。ggplot to 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) 

回答

4

为了节省ggplot数字,我会用ggsave。默认情况下,这会提取绘图设备的大小。因此,如果您在屏幕上的绘图设备中将纵横比设置为正确,则会转换为保存的图像文件。此外,它还支持通过输入参数width,heightdpi设置图像的宽度,高度和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) 
+0

也就是说,一般一个更好的选择。但是我停留在服务器上的旧版R(没有安装权限),它不支持'ggsave'。 我收到此错误讯息 'package'ggsave'不可用(对于R版本3.3.1)' 另外,我不想手动指定尺寸。它应该根据美学来选择尺寸。 – Shivendra

+0

'ggsave'不是一个单独的包,而是'ggplot2'中的一个函数。 –

+0

根据图自动选择正确的宽高比并不是很简单,而且还非常依赖于您的特定数据类型。据我所知,没有这样做的功能。然而,你可以尝试自己想出一些东西。 –