I have code below which saves an image to my pc. I would like to rotate that image by 45,90 and 135 degrees around its center (or bottom left hand corner) and then save as 3 different images. How could I do that?
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
png(width=50, height=50)
par(mai=c(0,0,0,0))
image(x)
dev.off()
---------update1-------------------------
Based upon the accepted answer the working code is as below
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
r1
x <- crop(r1, extent(0,ncol(r1),0,nrow(r1)))
plotRGB(x)
x1 <- 0:ncol(x)
y1 <- 0:nrow(x)
z <- matrix(1, nrow=length(x1), ncol=length(y1))
col.mat <- t(apply(matrix(rgb(getValues(x)/255), nrow=nrow(x), byrow=TRUE), 2, rev))
# Rotate 45 degrees
persp(x1, y1, z, zlim=c(0,2), theta = 20, phi = 90,
col = col.mat, scale=FALSE, border=NA, box=FALSE)
png("SaveThisPlot.png")
persp(x1, y1, z, zlim=c(0,2), theta = 20, phi = 90,
col = col.mat, scale=FALSE, border=NA, box=FALSE)
dev.off()
For the 90 degree rotations, this is an easy solution:
For the 45 degree and 135 degree rotation, it will be a bit trickier. There are probably other ways, but I'll use the
perspfunction and give different angles to thethetaargument.It's just a matter of setting up the call to
perspproperly.x1,y1, andzare just inputs for theperspfunction (see?perspfor more about the arguments to that function).col.matis a matrix holding color values.If you find that this is the mirror image of what you're looking for, try filling up the color matrix differently. For example:
As you can tell, filling up the color matrix properly is the key to making this approach work for you. I'll leave it as an exercise to the reader to figure out how to do any other manipulations to the color matrix.
Now, call
persp. Here, I set thezlimvalues so there is a range including 1. Because I made all thezvalues 1, you need to set a valid range, otherwise,perspwill throw an error about invalid limits. It doesn't like a range from 1 to 1.Here's a 135 degrees:
Saving the plots can be done in the same way you show in your question: