How to add a picture as datapoints in a map in R - 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.)

Related

R grid arrange tiff microscopy RGB

I have a RGB tiff files (from cellProfiler) which I want to import to R, label and arrange - as part of a high throughput analysis. The closest I get is using:
library(tiff)
library(raster)
imageTiff <- tiff::readTIFF(imagePath[i])
rasterTiff <- raster::as.raster(imageTiff)
raster::plot(rasterTiff)
raster::plot plots the image nicely but I can't catch the output and use it with gridExtra or add labels.
In addition I tried rasterVis with levelPlot and multiple other ways importing the tiff and then converting them to grob or ggplots.
However, I can't get anything to work and would like to ask if R is even suited at all for that task?
Thank you very much for your help!
Okay, I think that is the most straight forward way and possible also the most obvious one.
I import JPEG or TIFF files with jpeg::readJPEG or tiff::readTIFF respectively. Both transform the images to a raster format which is compatible with rasterGrid() and following grid.arrange etc.
library(jpeg)
library(tiff)
library(grid)
imageJPEG <- grid::rasterGrob(jpeg::readJPEG("test.jpeg"))
imageTIFF <- grid::rasterGrob(tiff::readTIFF("test.tiff"))
grid.arrange(imageJPEG , imageJPEG , imageJPEG)
grid.arrange(imageTIFF , imageTIFF, imageTIFF)
For my purpose that is perfect since tasterGrob does not alter the raster matrix values. Labeling might be a bit tricky but overall it is a grid/grob problem from here on.

How to put multiple existing graphs in a same plot?

This links explains how to plot multiple graphs in a same overall plot.
Now I have three existing graphs, png1, png2, png3. I want a layout like below. How to achieve this?
Thank you very much for the answer, please remember to install the packages:
install.packages("png")
library(png)
install.packages("gridExtra")
library(gridExtra)
After using the gridExtra, I combined three graphs together. However, they had very low resolution. How can I make them at least the same resolution as the original ones?
You would use the par or layout function. See the examples here: https://www.rdocumentation.org/packages/graphics/versions/3.5.0/topics/layout
If you're interested in inserting image files into the plot, you'd use readPNG and rasterImage and/or the grid raster functions.
Example:
png1 = png::readPNG("png1.png")
png2 = png::readPNG("png2.png")
png3 = png::readPNG("png3.png")
images = list(png1, png2, png3)
grobs = lapply(images, grid::rasterGrob)
gridExtra::grid.arrange(grobs=grobs)

R: world maps with ggplot2/ggmap - How to load a png image as a map

I am trying to find a workaround for ggmap's missing support of world maps (i.e. you can't create any maps that show latitudes > 80°, due to idiosyncrasies in the mapproj package).
To a limited extend however, it seems possible to create empty world maps and save them as an image (png etc.), even if you can't use the ggmap object directly as one normally would in ggmap(get_map(...)).
That's why I'd like to load a png (ideally, one I created with ggmap) into ggplot2 and use that as a map instead. How exactly can I do that?
I am aware that you can load background images in ggplot2 (see this stackoverflow question). But I'd also like to plot points on my map - it's important that the latitude/longitude values are mapped correctly.
(Notice: The code in this answer to World map with ggmap provides some code that, in terms of the output, comes close to what I had in mind.)
Here is an example without ggmap that you can use.
require(ggplot2)
require(cshapes)
world <- cshp(date=as.Date("2012-01-1"))
world.points <- fortify(world, region='COWCODE')
world.points2 <- merge(world.points,world#data,by.x="id",by.y="COWCODE",all.x=TRUE )
# Add a variable 'size' per country
world.points2$size <- factor(ifelse(world.points2$AREA < 121600,"small",ifelse(world.points2$AREA > 515000, "large", "medium")))
# Coord_fixed fixes the aspect ratio.
p <- ggplot(world.points2,aes(long,lat,group=group,fill=size)) + geom_polygon(colour="grey50") + coord_fixed()
p

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.

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

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.

Resources