I just started using googleVis in R, and am running into some trouble. I want to make a choropleth map of the departments of Honduras; here's my code:
map_me <- data.frame(prov=c("HN-AT","HN-CH","HN-CL","HN-CM","HN-CP","HN-CR",
"HN-EP","HN-FM","HN-GD","HN-IB","HN-IN","HN-LE",
"HN-LP","HN-OC","HN-OL","HN-SB","HN-VA","HN-YO"),
x=c(0.47,0.32,0.31,0.25,0.24,0.41,0.40,0.38,0.43,0.29,
0.17,0.25,0.33,0.17,0.19,0.39,0.21,0.31))
g <- gvisGeoChart(map_me,locationvar='prov',colorvar='x',
options=list(region="HN",dataMode="regions"))
plot(g)
In the browser window that pops up, the map is correctly zoomed-in on Honduras and the color scale in the legend shows the right limits (0.17-0.47). I think I have the correct ISO 3116-2 codes, based on the Wikipedia entry, but it seems to be having trouble connecting my data to the map locations.
Any ideas?
When all else fails, read the vignette. It turns out I needed to set the correct resolution option:
g <- gvisGeoChart(map_me,locationvar='prov',colorvar='x',
options=list(region="HN",resolution="provinces"))
Related
I'm following an example from Geocomputation with R in Chapter 4, section 4.2.6. In the example from the book, the map of New Zealand that has the average elevation in the polygons/regions has a nice, compact legend that is easy to read and placed automatically in the upper left corner. See the image output from the book below.
Here is the link to the section of the book: https://geocompr.robinlovelace.net/spatial-operations.html
When I execute the same code to try to duplicate this map, the image that is produced for me has a very distorted legend with text that is also small. I've tried adjusting my Plots pane, exporting the image in multiple formats, etc., and the legend is still distorted like this.
The code below is what I am executing:
library(sf)
library(spData)
library(tmap)
# Summarize nz regions by average elevation
nz_agg = aggregate(x = nz_height, by = nz, FUN = mean)
# Map nz regions colored by average elevation
tm_shape(nz) +
tm_polygons() +
tm_shape(nz_agg) +
tm_polygons(col = "elevation")
A couple months ago, when I produced tmaps with legends, I wasn't having this issue. I don't know if some setting has been changed or updated that I don't know about. The version of R that I'm using is 4.1.2 (2021-11-01) -- "Bird Hippie".
So, it wasn't a problem with my R version or the versions of the R packages I am using.
I use a laptop and have a couple of different locations where I use it for work. One location has multiple monitors; the other does not. I didn't notice it until researching this further, but when I plug in/unplug my monitors, sometimes it changes the resolution settings on my computer. Apparently, it wasn't enough for me to notice on my laptop until attempting to run this code. So, the cause of the distortion was due to changes on my computer that I was unaware of that happened automatically. I'll have to keep an eye on this.
Is there a way to (or what is the best way to) plot a map of a specific city, along with roads or neighborhood outlines?
I am pretty new to using R, so I've done a bit of Googling for an answer, but the ones I come up with don't work too well:
With ggmap, it appears I'd have to pay to get a good map. This is probably fine for me, but I'd be curious to see if there's a free way, such as with the maps package. I tried mapping a city (Minneapolis) with the maps package, but it came back with an error which I can't figure out how to get rid of, either through experimenting or Googling for help. Below is the code I did:
Minnesota <- subset(states, region %in% c("minnesota"))
which just kept coming back with Error: object 'states' not found. This was my first attempt to bring up a map of which I could zoom in on using the maps package. Does this mean maps didn't install correctly? Or is there something I'm missing?
I also tried using map, which I believe is part of ggplot2, with the code below:
map(database = "state", xlim = c(-93.0, -94.0), ylim = c(44.5, 45.5))
Again, this was to try and get a zoomed in map of a particular city, Minneapolis, but I kept getting the error "all data out of bounds". I assumed this was because the coordinates I entered were incorrect, but they line up with the coordinates of the city. What does it mean that all data is out of bounds?
The last thing I tried was using the package rworldmap. With the code below:
minneapolis <- getMap(resolution = "low")
plot(minneapolis, xlim = c(-93, -94), ylim = c(44.5, 45.5))
I think this one was actually working, the problem is that it's so zoomed in that I can't see the borders that come with the package/plot. Would there be a way to add roads/neighborhood borders to a map like this one? It seems like that would be the best way for me to build a map for free, but maybe I'm wrong.
Thank you for any help and clarification.
If you want the map to be interactive, then you should consider using leaflet, You can check this tutorial.
If you want it to be static ggmap or tmap are good options.
You do no need to pay. You can access the goole api or the OSM api and get the data.
Below is a JavaScript page I have created that allows me add and freely move markers on the map. From this map I can figure out the regions I am interested in.
Basically what I want to do is show the same map using ggplot2/MarMap with coastline indicators + bathymetry data. I am really just interested in getting bathymetry data per GPS location, basically getting negative/positive elevation per Lat+Long, so I was thinking if I can plot it then I should be able to export data to a Database. I am also interested in coastline data, so I want to know how close I am (Lat/Long) to coastline, so with plot data I was also going to augment in DB.
Here is the R script that I am using:
library(marmap);
library(ggplot2);
a_lon1 = -79.89836596313478;
a_lon2 = -79.97179329675288;
a_lat1 = 32.76506070891712;
a_lat2 = 32.803624214389615;
dat <- getNOAA.bathy(a_lon1,a_lon2,a_lat1,a_lat2, keep=FALSE);
autoplot(dat, geom=c("r", "c"), colour="white", size=0.1) + scale_fill_etopo();
Here is the output of above R script:
Questions:
Why do both images not match?
In google-maps I am using zoom value 13. How does that translate in ggplot2/MarMap?
Is it possible to zoom in ggplot2/MarMap into a (Lat/Long)-(Lat/Long) region?
Is it possible to plot what I am asking for?
I don't know how you got this result. When I use your script, I get an error since the area your are trying to fetch from the ETOPO1 database using getNOAA.bathy() is too small. However, adding resolution=1 (this gives the highest possible resolution for the ETOPO1 database), here is what I get:
To answer your questions:
Why do both images not match?
Probably because getNOAA.bathy() returned an error and the object dat you're using has been created before, using another set of coordinates
In google-maps I am using zoom value 13. How does that translate in ggplot2/MarMap?
I have no clue!
Is it possible to zoom in ggplot2/MarMap into a (Lat/Long)-(Lat/Long) region?
I urge you to take a look at section 4 of the marmap-DataAnalysis vignette. This section is dedicated to working with big files. You will find there that you can zoom in any area of a bathy object by using (for instance) the subsetBathy() function that will allow you to click on a map to define the desired area
Is it possible to plot what I am asking for? Yes, but it would be much easier to use base graphics and not ggplot2. Once again, you should read the package vignettes.
Finally, regarding the coastline data, you can use the dist2isobath() function to compute the distance between any gps point and any isobath, including the coastline. Guess where you can learn more about this function and how to use it...
I am plotting 2 maps side by side in lattice using an spplot command, using the simple default choropleth style color fill in sp. The syntax I am using is identical to this example:
library(sp)
library(rgdal)
library(lattice)
spplot(nc, c("SID74", "SID79"), names.attr = c("1974","1979"),
colorkey=list(space="bottom"), scales = list(draw = TRUE),
main = "SIDS (sudden infant death syndrome) in North Carolina",
sp.layout = list(arrow), as.table = TRUE)
The maps plot perfectly and exactly as intended side by side. However, I get a warning written on top of each of the maps as follows:
'Error using packet 1 length must be a 'unit' object'(on chart 1)
'Error using packet 2 length must be a 'unit' object' (on chart 2)
I apologize that I cannot give the data here to help troubleshoot. However, I was hoping someone might be able to point me in the right direction of figuring out what is going wrong.
Note: both maps chart perfectly fine as individual maps using the equivalent of:
spplot(nc,"SID74")
Clearly the problem is with the lattice view, but I am not familiar enough (despite having tried to look in Sarkar ch8) with packets to be able to know what is going wrong.
As an alternative, given that my charts are mapping as required, is there a way simply to turn off these warnings?
Many thanks for any help
http://rspatial.r-forge.r-project.org/gallery/#fig09.R gives the commands that reproduce your case. For me, with sp 1.1-1, everything works fine - I get the exact example figure.
If you did something with these data that causes this to malfunction, please report what you did, without that your question is misplaced.
Here, I found a landscape GIS layer is really attractive, especially for presenting species/samples distributions. I would like to know if it can be reached in R or any other resources?
The GIS layer were used in Fig 1. in this article (http://onlinelibrary.wiley.com/doi/10.1111/j.1469-8137.2010.03479.x/full).
This Fig 1 image is here:
http://onlinelibrary.wiley.com/store/10.1111/j.1469-8137.2010.03479.x/asset/image_t/NPH_3479_f1_thumb.gif?v=1&t=gsk5sbhs&s=e5e2e4bbb194f799f7ab9bec85a416e295405784
I have ever tried to submit this question in R-sig-geo. But, I failed. I expect to get some helps/directions here.
Thanks a lots for any directions.
Best wishes,
It is very possible to download this file and read it in with R, configure it to have the correct geo-coordinates so that overplotting works easily, and showing the image with the right colour scheme and so on. But, automating getting all of the data you need is not so easy.
You need the colour table from the GIF file so that you can plot the correct set of RGB values for each pixel (the information is in the file, but I'm not sure if this can be obtained directly with R, I will check - it certainly can be with GDAL, but extracting those values in an automated way depends on various tools being available).
UPDATE: It turns out that the raster package gets hold of the colour information correctly and plots it, see below.
You also need the geo-spatial information, i.e. the coordinates of a reference pixel (say, the top left pixel corner), and the scale (the geographic width and height of the pixels) and this information is not stored in the file. Also, the coordinate system of the file is not in the file, and very likely not provided explicitly with the image data.
If the colours and the coordinate system were stored with the file, then it would all be easy and something like the following would be enough.
(Note this worked for me once, but then I think subsequent requests are blocked by the server, so try to only download the file one time).
u <- "http://onlinelibrary.wiley.com/store/10.1111/j.1469-8137.2010.03479.x/asset/image_n/NPH_3479_f1.gif?v=1&t=gskxvi17&s=0f13fa9dae78bd6837aeee594065c6ca112864d2"
imfile <- paste(tempfile(), ".gif", sep = "")
download.file(u, imfile, mode = "wb")
library(raster) ## rgdal also required for this file format
library(rgdal)
im <- raster(imfile)
plot(im)
This looks fine but now see that there is no "real-world" coordinate system, this is just an axis from pixel 1 to the number in the X dimension (and same for Y).
axis(1, pos = 2)
So, still we need manually work to discover appropriate reference coordinates for the image - and guesses here can work fine, but still they are only guesses and you may end up creating a lot of pain for something seemingly simple.
If plot points interactively is enough for you, then you might use locator in conjunction with points and lines and text, and related plotting functions.
Feng,
if I read the Google docs correctly, you can modify the labels and displayed features with the extra parameters style and element.
I did not include custom parameters for these in the RgoogleMaps package, however, you can easily pass ANY addition parameters via the path argument !
If you read the help file for GetMap carefully, you will note the following example:
note that since the path string is just appended to the URL you can "abuse" the path argument to pass anything to the query, e.g. the style parameter:
#The following example displays a map of Brooklyn where local roads have been changed to bright green and the residential areas have been changed to black:
## Not run: GetMap(center='Brooklyn', zoom=12, maptype = "roadmap", path = "&style=feature:road.local|element:geometry|hue:0x00ff00|saturation:100&style=feature:landscape|element:geometry|lightness:-100", sensor='false', destfile = "MyTile4.png", RETURNIMAGE = FALSE);
Hope this helps,
Markus Loecher
If you just want data like this image, then there are packages to access imagery directly, again utilizing the tools in sp and rgdal. This example is close using gmap in the dismo package.
library(dismo)
e <- extent(-7, 5, 38, 44)
gm <- gmap(e, type = "terrain")
plot(gm)
Note that while we specify the extents in "longlat" the image comes back in its native (Google) Mercator.
print(gm)
See ?gmap for more options on transforming your own data to match the image's projection, or the broader function set in raster, rgdal and sp for other options. There are other imagery providers that might be preferable, and quite a few options in the R suite of contributed packages.