R:裁剪多个PNG并将它们组合成一个图 [英] R: crop multiple pngs and combine them into a single plot

查看:213
本文介绍了R:裁剪多个PNG并将它们组合成一个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数据绘制成两个图,如下所示:

I am plotting data into two plots like this:

xy <- structure(list(NAME = structure(c(2L, 2L, 1L, 1L), .Label = c("CISCO", "JOHN"), class = "factor"), ID = c(41L, 41L, 57L, 57L), X_START_YEAR = c(1965L, 1932L, 1998L, 1956L), Y_START_VALUE = c(960L, -45L, 22L, -570L), X_END_YEAR = c(1968L, 1955L, 2002L, 1970L), Y_END_VALUE = c(960L, -45L, 22L, -570L), LC = structure(c(1L, 1L, 2L, 2L), .Label = c("CA", "US"), class = "factor")), .Names = c("NAME", "ID", "X_START_YEAR","Y_START_VALUE", "X_END_YEAR", "Y_END_VALUE", "LC"), class = "data.frame", row.names = c(NA,-4L))
ind <- split(xy,xy$ID)
# Plots
for (i in ind){
  xx = unlist(i[,grep('X_',colnames(i))])
  yy = unlist(i[,grep('Y_',colnames(i))])    
  fname <- paste0(i[1, 'ID'],'.png')
  png(fname, width=1679, height=1165, res=150)
  par(mar=c(6,8,6,5))
  plot(xx,yy,type='n', xlab=NA, ylab="Value [mm]",ylim = range(c(yy,-.5,.5))) 
  i <- i[,-1]
  segments(i[,2],i[,3],i[,4],i[,5],lwd=2)
  abline(h=0)
  dev.off()
} 

之后,我将生成的png像这样添加到一个png文件中.

After that I am adding the resulting pngs into one png file like this.

library(grid)
library(png)
plots <- lapply(ll <- list.files(patt='.*[.]png'),function(x){
  img <- as.raster(readPNG(x))
  rasterGrob(img, interpolate = FALSE)
})

library(ggplot2)
library(gridExtra)

ggsave("Plots_Combined.png",width=8.5, height=11, 
       do.call(marrangeGrob, c(plots, list(nrow=2, ncol=1,top=NULL))))

我的问题:我想知道在R中创建单个png后是否有一种裁剪这些png的边的方法吗?我知道您可以通过更改mar参数在绘图循环中更改此设置,但是我想知道是否可以在创建png之后在外部执行此操作?我主要感兴趣的是裁剪图1的下部(41.png)和图2的上部(57.png)->下面的示例草图中的红色区域应被裁剪.可以在生成的png(例如title)中添加标题或简单文本吗?

My question: I was wondering if there is a way of cropping the sides of the single pngs after they are created in R? I know that you could change this in the plot loop by changing the mar parameters, but I was wondering if you could also do this outside after the pngs are created? I would be mainly interested in cropping the lower part of plot 1 (41.png) and the upper part of plot 2 (57.png) -> red area in the sample sketch below should be cropped. Is it possible to add a title or simple text to the resulting png (e.g. title)?

推荐答案

您可以对图像进行子集

img <- readPNG(system.file("img", "Rlogo.png", package="png"))
grid.raster(img[10:50,20:90,])

这篇关于R:裁剪多个PNG并将它们组合成一个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆