问题
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()
}
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))))
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)?
回答1:
you can subset the image,
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
grid.raster(img[10:50,20:90,])
来源:https://stackoverflow.com/questions/27496127/r-crop-multiple-pngs-and-combine-them-into-a-single-plot