我正在生成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)
答案 0 :(得分:8)
为了保存ggplot
数字,我会使用ggsave
。默认情况下,这会获取绘图设备的大小。因此,如果您在屏幕上的绘图设备中设置正确的宽高比,则会转换为已保存的图像文件。此外,它还支持通过width
,height
和dpi
输入参数设置图像的宽度,高度和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)