R : How to Plot a Zoomed in Map of a City - r

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.

Related

Mapping in R with maps package

I am currently trying to generate a map in R demonstrating where my different sampling locations are along the east coast of Canada. I had my code working previously yesterday and was able to visualize the specific area I wanted to look at, and then layer my point on top.
This morning however, when I open the project back up and try to generate the map with this line of code:
map("worldHires", "Canada", xlim=c(-80,-45), ylim=c(40,60), col="gray90", fill=TRUE)
I get the output [[1]] NULL. This is not trying to plot the sampling locations yet, just generating a blank map which I will plot the points over. All the necessary packages (to my knowledge) are loaded (maps, mapdata, maptools, scales) and I don't understand why it was working fine yesterday but today I am only getting this output. I have tried with other regions as well and no matter what I put into the argument it only returns NULL.
I have also tried just entering the line:
map("world", xlim=c(-80,-45), ylim=c(40,60), interior=TRUE)
However when I do this I get this error: Error in as_mapper(.f, ...) : argument ".f" is missing, with no default (which makes sense to me given that this line of code seems to be missing the argument of where it is drawing the geographical data from)
Any tips on what to do? I don't understand why it would be returning a NULL result and I haven't been able to find much help online so far.

r: Displaying Eastern Russia and North America on one map rnaturalearth

I'm still learning how to use R. I'm trying to display points in North America and Eastern Russia using the package "rnaturalearth". I'd like to just show Russia and North America, rather than all of Europe. I've included a picture with the area of the world that I want in a box here. I get this error whenever I input positive and negative longitude values.
Error in st_normalize.sfc(x, c(x_range[1], y_range[1], x_range[2], y_range[2])) :
domain must have a positive range
I couldn't find anything online, although I'm sure it's probably pretty simple. Any help would be appreciated!
Here is the code for the general mapping:
world <- ne_countries(scale = "medium", returnclass = "sf")
ggplot(data = world)+
geom_sf()+
coord_sf(xlim = c(160, -60), ylim = c(20, 90), expand = FALSE)
I had almost the exact same challenge to try and solve and found your question while trying to figure it out. Here are the links which helped me get the output I wanted. I won't give an exact solution myself as I think these links already have the solution well laid out.
This question contains almost the exact process you are looking for:
https://gis.stackexchange.com/questions/332106/union-anti-meridian-multipolygons-after-re-centering-world-map
This is what the individual in the above question used as a reference to edit the code from (which also includes the packages needed to do this):
https://github.com/valentinitnelav/valentinitnelav.github.io/blob/master/gallery/Shift%20central%20(prime)%20meridian.R#L73
Once you have the polygons shifted you can use "coord_sf()" as you tried before to get the subset of the map you want.
The only issue I have with this specific solution is that it will shift the longitude values on the map. This means they do not accurately represent the actual longitude values. So make sure to take that into account if you want to show the longitude values on the map.
I hope this helps you get the map you want!
Edit: I just remembered this site has a different way to get a similar solution under "Example of a failed transformation", depending on the map projection you want.
https://mgimond.github.io/Spatial/coordinate-systems-in-r.html

Google Maps vs. ggplot2/MarMap

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

How to fill the blank in choropleth in r ? ggplot2 and maps

Anyone can tell me how do I fill the blank field in my choropleth? I have attached a picture for the choropleth I created.Thanks a lot!
I noticed the statename in two tables do not match, but I am not able to change the statename in my raw data.
library(ggplot2)
library(maps)
**#Data looks like this:**
aggrev2015<-data.frame(
statename=c("alabama","alaska","arizona","arkansas","california","colorado","connecticut","delaware","florida","georgia","hawaii","idaho","illinois","indiana","iowa","kansas","kentucky","louisiana","maine","maryland","massachusetts","michigan", "minnesota","mississippi","missouri","montana","nebraska","nevada","new hampshire","new jersey","new mexico","new york","north carolina","north dakota","ohio","oklahoma", "oregon","pennsylvania","rhode island","south carolina","south dakota","tennessee","texas","utah","vermont","virginia","washington","west virginia","wisconsin","wyoming"),
revenue=runif(50,min=100,max=9000))
state_df <- map_data("state")
colnames(state_df)<-c("long","lat","group","order","statename","subregion")
choropleth <- merge(aggrev2015,state_df, by = "statename")
ggplot(choropleth, aes(long, lat, group = statename)) +
geom_polygon(aes(fill = revenue))
At first glance your problem seems related to states that have islands. Rather than debug that, I'll follow up on #hrbrmstr's suggestion of using choroplethr:
library(choroplethr)
library(choroplethrMaps)
data(df_pop_state)
state_choropleth(df_pop_state)
You can see more documention on creating state choropleths with the choroplethr package here, and the package has an email course as well.
For state choropleths, I think that the main advantage of the package over doing it yourself is demonstrated in the above vignette: It makes exploratory data analysis much easier. For example, changing the scale or zooming becomes as easy as setting parameters on a function. The package also includes AK and HI as well as uses a sensible projection. Solving these problems tends to be a headache when doing it all yourself in ggplot2. Note that I am the author of choroplethr, so I speak from experience :)
Another thing to point out is that you might want to overlay your choropleth over a reference map, such as those from google maps. I recently added that functionality to the latest version of choroplethr. But I haven't had a chance to update the package vignettes to explain how to use it. To get the default reference map just set reference_map = TRUE:
data(continental_us_states)
state_choropleth(df_pop_state,
zoom = continental_us_states,
reference_map = TRUE)
If you wanted to use a different reference map (such as a satellite map), you can do that to. I just wrote a blog post on it. This is the most common question I got after implementing the reference map feature a few weeks ago.

Error in packets in spplot using lattice

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.

Resources