Is it possible to rotate a plot in R (base graphics)? - r

I searched for this and found that with {grid} there are ways to rotate an image, and that for some plots you can play with their rotation (for example plot(x,y) instead of plot(y,x)).
However, I want to know if there is a generic method to rotate a plot in R (one that would work for ANY plot generated in base graphics) ?

you could export the graphic, read it back in, and display it rotated as a rasterGrob, say, (or a rasterImage after rotating the matrix, or a grImport grob if you want vector paths)
plot(1:10, rnorm(10))
library(grid)
cap <- grid.cap()
grid.newpage()
grid.raster(cap, vp=viewport(angle=30))
The new gridGraphics package may now be a better alternative.
Note: this doesn't seem to work with Rstudio's graphics device, presumably they haven't implemented grid.cap.

It's kind of possible via the gridGraphics package, although it feels a bit rough on the edges (the examples in ?grid.echo don't all work for me),
plot(1:10, rnorm(10))
library(gridGraphics)
grab_grob <- function(){
grid.echo()
grid.grab()
}
g <- grab_grob()
grid.newpage()
pushViewport(viewport(width=0.7,angle=30))
grid.draw(g)

I'm reasonably certain that there isn't a way with base graphics itself to do this generically. There is however the gridBase package which allows one to mix base graphics and grid graphics in a 'plot'. The vignette for the package has a section on embedding base graphics in grid viewports, so you might look there to see if you can cook up a grid wrapper around your plots and use grid to do the rotation. Not sure if this is a viable route but is, as far as I know, the on only potential route to an answer to your Q.
gridBase is on CRAN and the author is Paul Murrell, the author of the grid package.
After browsing the vignette, I note one of the bullets in the Problems and Limitations section on page, which states that it is not possible to embed base graphics into a rotated grid viewport. So I guess you are out of luck.

Spinning 3D Scatterplots
You can also create an interactive 3D scatterplot using the plot3D(x, y, z) function in the rgl package. It creates a spinning 3D scatterplot that can be rotated with the mouse. The first three arguments are the x, y, and z numeric vectors representing points. col= and size= control the color and size of the points respectively.
# Spinning 3d Scatterplot
library(rgl)
plot3d(wt, disp, mpg, col="red", size=3)

A function rotate_plot to be used like
rotate_plot(some_base_plot(x, y, ...))
isn't possible because most of the base plot don't return a value.
Some of the plots contain a horiz argument to allow you to choose which way round you want the plot drawing. Take a look at barplot.default to see how to implement this. (Warning: it's messy.)
#ucfagls's suggestion to use gridBase is your best bet. There are some examples of its use in Appendix B of Murrell's R Graphics.

Given that its possible to write your own plot functions using base graphics, I can't see how a single solution could exist. Is what you want really just a way to rep lace x data with y data? What exactly do you mean by "rotate"?

Yes it is possible to rotate the the plot in R
by using the function Coord flip() in r
you can flip the graph from horizontal to vertical and from vertical to horizontal.

Related

How to determine x, y coordinates when adding text in metafor

I’m using the metafor package to create Forest plots in R. I’d like to add text to my plots to create labels using the text() function. I’m wondering what the simplest way is to determine the x,y coordinates of where I want my text to go. Currently I just guess and see how it looks and then edit as necessary. Is there a way to overlay a grid over my plot or something to guide me (and then remove it after)?
Thank you!
Start by saving what forest() returns:
x <- forest(res)
And then take a look at x. Among other things, it contains xlim and ylim, which are the x-axis and y-axis limits. Try this:
abline(v=x$xlim)
abline(h=x$ylim)
Also useful:
text(x$xlim[1], x$rows, x$rows, xpd=NA)
I hope this helps.

Displaying multiple 3d plots in the same window using plot3D {rasterVis} in R

I am interested in making two 3d topographic plots that display side by side in the same Xquartz device window. Displaying two 3d plots in the same window is straightforward using the rgl package - there are plenty of examples in the documentation using mfrow3d() and other methods.
However, I need to use the plot3D() function from the rasterVis package. The reason I am using plot3D() from rasterVis, rather than something like surface3d() from rgl, is that I need to use the drape argument in plot3D() to display values from a raster as colors on a 3d topographic map (and this raster has different values than the one that creates the z axis on the plot). If anyone has tips on something analogous to drape within an rgl function, I would also be interested in that!
When I try to use mfrow3d() along with the plot3D() function, it brings up a series of blank device windows instead of displaying the two plots side by side in the same window.
Here is some code to make a topographic map using plot3D, from the rasterVis documentation:
data(volcano)
r <- raster(volcano)
extent(r) <- c(0, 610, 0, 870)
levelplot(r, col.regions=terrain.colors)
plot3D(r)
And here is where I try to use mfrow3d to plot 2 identical volcano plots side by side, one in blue and one in red, which I adapted from the rgl documentation:
volcanos <- list(r, r)
col <- c("blue", "red")
open3d()
mfrow3d(1,2)
for (i in 1:2) {
next3d()
plot3D(volcanos[[i]], col=col[i])
}
Is what I am trying to do even possible with plot3D from rasterVis?
The current version of rasterVis::plot3D opens a new device with each call. I have modified its code to test if there is an active device, and open a new one only if needed. With this commit your example works as expected. You should install the development version of rasterVis with devtools::install_github('oscarperpinan/rasterVis').

R_plotting points in multiple plots

I have two plots and I want to add some additional lines to both plots. Is there a way in R to choose the plot (among the two) to draw the new lines?
Edit1:
Actually I have multiple plots in one window using mfrow
Edit2:
I have edited the the question to include the problem i faced after using mfgin par()
x=1:10
y=seq(10,100,10)
z=seq(100,1000,100)
par(mfrow=c(2,1))
plot(x,y)
abline(a=0,b=10,col="blue")
plot(x,z)
abline(a=0,b=100,col="blue")
which gives
But when I use
x=1:10
y=seq(10,100,10)
z=seq(100,1000,100)
par(mfrow=c(2,1))
plot(x,y)
plot(x,z)
par(mfg=c(1,1))
abline(a=0,b=10,col="blue")
par(mfg=c(2,1))
abline(a=0,b=100,col="blue")
the result is
Note the false behavior of the first abline
Can anyone explain the reason and a solution for this?
Assuming you have multiple graphics windows open, you want to use the dev.cur(), dev.next(), dev.set(), dev.list() functions (see ?dev.cur) to identify the current graphics device and switch among devices.
If on the other hand you have set up multiple plots within a single window via the mfrow or mfcol parameters to par(), you can use par("mfg") to query/set which plot is current.
If you use layout, lattice, ggplot2, or raw grid graphics, I'm not sure.

How to add a picture as datapoints in a map in R

I am using maps package in R to draw a simple geographic map and then put my data points in it.
My question is that whether there is any way in R to represent data points with a picture of interest, for example, the animal I am working on in my example.
This is just to give a better representation of the distribution of my data points relative to each other for my reader.
You can also use grid package. The grid.raster can be used to put some pictures.
Since maps is graphic base package , you need to gridBase to combine the grid/base graphics.
Here an example:
library(maps)
map('usa',boundary=T,fill=T,col='grey')
library(gridBase)
library(grid)
library(png)
vps <- baseViewports()
pushViewport(vps$figure,vps$plot)
camel <- readPNG("camel.png") ## some animal picture
grid.rect(gp = gpar(fill=NA))
x <- c(-110,-100,-70)
y <- c(30,40,40)
grid.raster(image=camel,x=x,y=y,width=5, ## it is vectorized
interpolate=FALSE,default.units = 'native')
upViewport(1)
PS: I am not sure that there are camels in USA...
rasterImage is one way, albeit somewhat laborious. Once you've got the images of interest formatted as raster objects, you can then place them at designated locations (and frame sizes) inside your plot region.
In addition to the rasterImage function mentioned by #CarlWitthoft there is also the combination of my.symbols and ms.image from the TeachingDemos package for adding images to a plot (base graphics). The rasterImage approach gives the most control, but my.symbols is more like the regular plotting functions in that you say plot the images centered at these coordinates (and set other options to specify size etc.)

Plotting sized squares on Google-maps

I need to plot many squares of different colors on Google-maps, these commands work well:
library(RgoogleMaps)
Map <- GetMap.bbox(bb$lonR, bb$latR, zoom=zoom, maptype="terrain", NEWMAP=TRUE)
tmp <- PlotOnStaticMap(lat=tbl_to_plot$lat, lon=tbl_to_plot$lon, cex=2, pch=15, col=tbl_to_plot$color, MyMap=Map, add=TRUE, NEWMAP=FALSE, FUN=points)
Choosing pch=15 results in the points becoming squares (good). The challenge is that I need each square to be exactly 100x100 meters big, and as the underlying maps can be of different zoom, it needs to be set automatically. I suppose it is the cex-value I should change, but I don't understand what unit it has.
Thanks to all R-users here at Stack Overflow for a fantastic source of help!
The PlotOnStaticMap function uses base graphics, in which sizes of points are a little fuzzy. If you need to accurately specify the size of your squares, you need to use a grid-based graphics package (either lattice or ggplot2).
There's a good demo of using RgoogleMaps with ggplot2 here.

Resources