ggplot到png-自动拉伸图像 [英] ggplot to png - automatically stretching image
问题描述
我正在生成一个ggplot plot
并将其另存为.png
图像.在Rstudio中生成的图根据y轴上的值拉伸时,将其另存为.png
时,我得到一个正方形的图像.
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
.
如何以.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)
推荐答案
为保存ggplot
数字,我将使用ggsave
.默认情况下,这将获取绘图设备的大小.因此,如果您在屏幕上的绘图设备中设置了正确的长宽比,这将转换为保存的图像文件.此外,它支持通过width
,height
和dpi
输入参数设置图像的宽度,高度和dpi.
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.
例如:
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)
这篇关于ggplot到png-自动拉伸图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!