Plotting sized squares on Google-maps - r

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.

Related

cluster: :clusplot axis in wrong direction

I'm trying to plot the cluster obtained from fuzzy c-means clustering.
The plot should look like this.
code for the plot
plot(data$Longitude, data$Latitude, main="Fuzzy C-Means",col=data$Revised, pch=16, cex=.6,
xlab="Longitude",ylab="Latitude")
library(maps)
map("state", add=T)
However, when I tried to use clusplot the plot is displaying in opposite direction(both top and bottom and left and right) as below.
I wanna know if there's a way to reverse the plot to show in the order as the above picture.
Also, for the very dense area, it's hard to find the ellipse label. I wanna know if there's a way to show the label inside the ellipse instead of outside.
code for 2nd pic
library(cluster)
clusplot(cbind(Geocode$Longitude, Geocode$Latitude), cluster, color=TRUE,shade=TRUE,
labels=4, lines=0,col.p=cluster,
xlab="Longitude",ylab="Latitude",cex=1)
clusplot is a function that performs a lot of magic for you. In particular it projects the data set - which happens in a way you don't like, unfortunately. (Also note the scales - it centered and scaled the data, too)
clusplot.default: Creates a bivariate plot visualizing a partition (clustering) of the data. All observation are represented by points in the plot, using principal components or multidimensional scaling.
As far as I can tell, clusplot doesn't have map support, but you will want such a map I guess...
While maybe you can use the s.x.2d parameter to specify the exact projection (and this way disable automatic scaling), it probably is still difficult to add the map. Maybe look at the source of clusplot instead, and take only the parts you want?

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.)

Drawing circles in R

I'm using plotrix package to draw circles.
And I don't get what is wrong with my code... :-(
I have three points. The first point (1,1) should be the center of the circle. The following two points (1,4) and (4,1) have the same distance/radius to the center.
So the circle in the plot should go through these points, right?
And I don't know why the circle looks wrong. Is there an explanation?
p1 <- c(1,1)
p2 <- c(4,1)
p3 <- c(1,4)
r <- sqrt(sum((p1-p2)^2))
plot(x=c(p1[1], p2[1], p3[1]),
y=c(p1[2], p2[2], p3[2]),
ylim=c(-5,5), xlim=c(-5,5))
draw.circle(x=p1[1], y=p1[2], radius=(r))
abline(v=-5:5, col="#0000FF66")
abline(h=-5:5, col="#0000FF66")
Take a look at the produced output here
As #Baptiste says above, you can use plot(...,asp=1). This will only work if your x and y ranges happen to be the same, though (because it sets the physical aspect ratio of your plot to 1). Otherwise, you probably want to use the eqscplot function from the MASS package. A similar issue arises whenever you try to do careful plots of geometric objects, e.g. Drawing non-intersecting circles
This plot is produced by substituting MASS::eqscplot for plot in your code above:
Note that depending on the details of what R thinks about your monitor configuration etc., the circle may look a bit squashed (even though it goes through the points) when you plot in R's graphics window -- it did for me -- but should look OK in the graphical output.

R - Scatter plots, how to plot points in differnt lines to overlapping?

I want to plot several lists of points, each list has distance (decimal) and error_no (1-8). So far I am using the following:
plot(b1$dist1, b1$e1, col="blue",type="p", pch=20, cex=.5)
points(b1$dist2, b1$e2, col="blue", pch=22)
to add them both to the same plot. (I will add legends, etc later on).
The problem I have is that points overlap, and even when changing the character using for plotting, it covers up previous points. Since I am planning on plotting a lot more than just 2 this will be a big problem.
I found some ways in:
http://www.rensenieuwenhuis.nl/r-sessions-13-overlapping-data-points/
But I would rather do something that would space the points along the y axis, one way would be to add .1, then .2, and so on, but I was wondering if there was any package to do that for me.
Cheers
M
ps: if I missed something, please let me know.
As noted in the very first point in the link you posted, jitter will slightly move all your points. If you just want to move the points on the y-axis:
plot(b1$dist1, b1$e1, col="blue",type="p", pch=20, cex=.5)
points(b1$dist2, jitter(b1$e2), col="blue", pch=22)
Depends a lot on what information you wish to impart to the reader of your chart. A common solution is to use the transparency quality of R's color specification. Instead of calling a color "blue" for example, set the color to #0000FF44 (Apologies if I just set it to red or green) The final two bytes define the transparency, from 00 to FF, so overlapping data points will appear darker than standalone points.
Look at the spread.labs function in the TeachingDemos package, particularly the example. It may be that you can use that function to create your plot (the examples deal with labels, but could just as easily be applied to the points themselves). The key is that you will need to find the new locations based on the combined data, then plot. If the function as is does not do what you want, you could still look at the code and use the ideas to spread out your points.
Another approach would be to restructure your data and use the ggplot2 package with "dodging". Other approaches rather than using points several times would be the matplot function, using the col argument to plot with a vector, or lattice or ggplot2 plots. You will probably need to restructure the data for any of these.

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