如何在R中创建缩略图?

时间:2011-03-31 17:45:00

标签: r thumbnails plot

我正在尝试使用R图生成.png文件。这非常有效:

png(file="hello.png", width=1000, height=800)

# Lots and lots of plotting. Long code. Very slow.
plot(x=c(1, 2, 3), y=c(4, 6, 5))

dev.off()

现在如何直接从R获取hello.png的缩略图?

3 个答案:

答案 0 :(得分:3)

我不确定这会如何扩展到您的实际应用程序,并且对png库没有太多经验,但这对我的测试用例来说相当快。您需要指定要制作缩略图的PNG文件的名称以及该缩略图的高度/宽度。默认情况下,它会将缩略图保存在文件名前加thumb_的同一目录中。

makeThumb <- function(file, height, width) {
  require(png)
  img <- readPNG(file)

  png(file = paste("thumb", file, sep = "_"), height = height, width = width)
    par(mar=c(0,0,0,0), xaxs="i", yaxs="i", ann=FALSE)
    plot(1:2, type='n', xaxt = "n", yaxt = "n", xlab = "", ylab = "")
    lim <- par()
    rasterImage(img, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
  dev.off()
}

如果这对您有用,请告诉我。该函数适用于lapply,同时也可以对目录中的大量文件进行操作:lapply(listOfFiles, makeThumb, height = 200, width = 200)

答案 1 :(得分:2)

您可以将图表写入文件两次,大小不同。

#wrap your plotting code into a function
my_plot <- function()
{
  #whatever
}

plot_file_name <- "hello.png"
png(file = plot_file_name, width = 1000, height = 800)
my_plot()
dev.off()

png(file = paste("thumb", plot_file_name, sep = "_"), width = 40, height = 32)
my_plot()
dev.off()

此技术可以更好地与latticeggplot2一起使用,其中my_plot可以返回绘图对象,因此您无需再调用该函数两次,即调用

a_plot <- myplot()
png(...)
print(a_plot)
dev.off()

编辑:有几种不同的“缩放”方式。这是一个ggplot2工作流示例。

绘制并保存你的情节

myplot <- function()
{
  #e.g.,
  ggplot(cars, aes(speed, dist)) + geom_point()
}

the_plot <- myplot()

ggsave("full plot.png", the_plot)    

您可能希望将geom size更新为

scale_factor <- 0.1
update_geom_defaults("point", aes(size = 2 * scale_factor))

您可以使用opts_full包中的ggExtra仅显示面板内容(即忽略轴,标题和图例)。

ggsave("thumbnail panel only.png", the_plot + opts_full(), scale = scale_factor)

另一种方法是尝试减小轴的尺寸等。不幸的是,这有点痛苦。

theme_mini <- theme_grey(12 * scale_factor)
theme_mini$axis.ticks.length <- scale_factor * theme_mini$axis.ticks.length   
theme_mini$axis.ticks.margin <- scale_factor * theme_mini$axis.ticks.margin
theme_mini$panel.margin <- scale_factor * theme_mini$panel.margin 
theme_mini$plot.margin <- scale_factor * theme_mini$plot.margin
#and probably some more elements to resize

ggsave("thumbnail updated theme.png", the_plot + theme_mini, scale = scale_factor)

答案 2 :(得分:1)

您可以使用dev.copy实用程序:

png("plot_large.png",1000,1000)
dev.control("enable")

# ..... start of plot section .....
plot(rnorm(100))
# ..... end of plot section .....

dev.copy(png, filename="plot_small.png", width=100, height=100)
dev.off()
dev.off()

您遇到的问题与Chase answer相同,但此处par参数化影响两个图

第二件事是关于dev.copy帮助页面的说明:

  

请注意,这些功能会复制   设备区域而不是情节:   设备的背景颜色   表面是复制的一部分。   大多数屏幕设备默认为a   透明的背景,这是   可能不是什么时候需要的   复制到png等设备。

第三 - 这不完全是缩略图因为png大小决定了一些参数(这就是为什么你得到“数字边距太大”的错误)。所以我个人认为你应该使用外部图像处理工具。