R: Set X and Y limits when using qmap (ggplot2) - r

I'm trying to create a map using the qmap (part of ggmap).
Here's an example piece of code to illustrate by question. It's kind of silly, but it's cleaner than using my own data.
install.packages("ggmap")
library(ggmap)
qmap("Capitol Building, Washington DC", zoom = 15)
So here's my question:
I'd like to zoom in a good bit (zoom=15) on the area around the Capitol Building, to get lots of street detail.
But I also want to include the Washington Monument in my map.
To do this, I'd like to extend the western part of the map and make it rectangular.
Does anybody know how to do that? Any insight would be much appreciated. Thanks for your patience with a beginner.

Like this?
library(ggmap)
cap <- geocode("Capitol Building, Washington DC")
wash <- geocode("Washington Monument, Washington DC")
loc <- unlist((cap+wash)/2)
ggmap(get_map(location=loc,zoom=15))+coord_fixed(ylim=loc[2]+.005*c(-1,+1))
So this pulls in a map based on coords midway between the Capitol Building and the Washington Monument, then trims it by setting the ylim.
The reason for unlist(...) is that geocode(...) returns a data frame and get_map(...) wants a numeric vector.
EDIT Response to OP's comment.
coord_fixed(...) forces an aspect ratio of 1:1, meaning that 1° of latitude is the same length as 1° of longitude. To get back the original aspect ratio from the map, use coord_map(...).
ggmap(get_map(location=loc,zoom=15))+coord_map(ylim=loc[2]+.005*c(-1,+1))

Related

Lost data within a spatial polygon

Hopefully the following makes sense and apologies if not!
I have a dataset of GPS locations (of various species footprints), and am measuring the distance from where each point was found to the boundary of a national park in R. Im doing this with a series of environmental factors, (roads/villages/lakes etc), and for all other enviro variables (and kml files) Ive had no problems, however when I run my park boundary data, (using a kml file read in as a spatial polygon of the national park), I keep getting negative values for all the GPS points that occur within the park boundary? (So anything within the polygon essentially). The results output I am getting shows the correct measurements from GPS points to the boundary that occur on the OUTSIDE of the boundary, (or polygon), but anything inside the park/polygon outputs as a zero value. Ive tried to reproject the polygon as just an outline and tried removing the 'fill' etc, along with a few other tricks Ive found, but no luck so far?
Am I correct in assuming the data is just not there and that I need to recreate the boarder of the park some other way? Or is it more an issue with how Im asking r to calculate the distance measurements?
Below is an example of the code I am using
KSNP_Poly <- readOGR("KSNPboundaryexport.kml")
Points <- read.csv("AllPoints.csv")
sptsPoints = SpatialPoints(Points)
plot(KSNP_Poly)
plot(sptsPoints)
apply(gDistance(sptsPoints,KSNP_Poly,byid=TRUE),2,min)
KSNPResults <- apply(gDistance(sptsPoints,KSNP_Poly,byid=TRUE),2,min)
Hope this made sense and any advice greatly appreciated!
Thanks!
Kass

Voronoi approach to making districts while also using a multilinestring

I have a spatial objects with multiple points (buildings) on a map. What I wanted to do is divide an area based on the nearest point. The calculated Voronoi looks quite promising, but has some strange aspects if you know the "real world". For example a small part of a district is also at the other side of a river because of the closeness (surprise).
What I want to do is combine this with a multi linestring which contains rivers, railroads. What I want to do either end the district at this line OR add a penalty for 'crossing' it. Is anyone able to shed light on the problem, or possible suggest an alternative voronoi method that works?

Mapping how many points are within a radius of every location in R

In R, I am trying to create a choropleth map. I have built a database of businesses, some are part of chains (e.g. McDonalds) and others are independent. I want to calculate how many businesses are within 30km of each point on the map, but treat the different locations of chains as a single business.
For example, if you a point is:
5km from a McDonalds,
10km from Taco Bell
15km from Chick-Fil-A
20km from KFC
25km from McDonalds
35km from Five Guys
The colour will show that there are 4 fast food outlets within 30km.
I am happy to use any R package but I am mostly familiar with tmaps and ggplot2 maps.
At this stage the best approach I can think of is to create polygons for each chain and stack them as transparent layers of the same colour. I don't think this would be very efficient and wouldn't create a very nice looking choropleth.
The other answers I could find were either counting points (e.g https://gis.stackexchange.com/questions/229066/counting-how-many-times-a-point-is-inside-a-set-of-intersecting-polygons-in-r) or for GIS software.
EDIT:
I have managed to create a 30km radius from every location of every chain (using rgeos gIntersection). I now have a series of polygons.
To solve my question the additional thing I need to do is create polygons for where:
Only one polygon covers the area,
Two polygons covers the area,
etc.
To try to visual is this I used the answer from https://gis.stackexchange.com/questions/229066/counting-how-many-times-a-point-is-inside-a-set-of-intersecting-polygons-in-r
In the linked question they are trying to count how many polygons cover the numbered points (the image on the right). What I am trying to do is to create the image on the left, where there are polygons of no overlap (1), two overlapping polygons (2) and so on.
I think what you are trying to accomplish would be best approached using a raster approach rather than a chloropleth. To make a chorlopleth, you define a set of (generally irregular) polygons, summarize something within each polygon, then color the polygons based on the attributes. This would be a good approach if you wanted to say how many fast food resteraunts are within each state or county, or how many fast food joints per capita by state.
From your description, however, you are looking for how many fast food joints within a set radius for all points. This is more of a raster question, since you can represent your data on a regular grid.
The raster package is a good start for working with raster data and works well with the sf package.
You need to determine what density you need to accomplish your goal, then use this to determine the resolution of your raster. Once you've got that you can use raster::rasterize() to summarize your (I'm assuming) point data.
I'm assuming you have an object that has the locations of each restaurant, I'll call this object "points".
library(raster)
library(sf)
# create raster template with 30km resolution (I'm assuming your projection is in meters)
raster_template = raster((extent(points),
resolution = 30000,
crs = st_crs(points)
)
# rasterize your point data
r = rasterize(points, raster_template, fun = "count")
This should create a grid where each cell has the number of points within each 30km cell. You should then be able to plot the raster, but may want to either clip or mask it to just show parts that are within New Zealand

Feature engineering of X,Y coordinates in neighborhoods of San Francisco

I am participating in a starter Kaggle competition(Crimes in San Francisco) in which I want to predict the category of a crime using a bunch of predictor variables including X and Y coordinates of a crime. As I doubt of the predictive power of the coordinates, I want to transform these variables to something more relevant to the crime category.
So I am thinking that if I had the neighbourhood of San Francisco in which the crime took place, it would be more informative than the actual coordinates of the crime. I can find the neighbourhoods online but of course I cant use the borders of each neighbour to classify the corresponding crime because their shapes are not rectangular or anything like that.
Does anyone have any idea about how I could solve this one?
Thanks guys
Well that's interesting AntoniosK and it's getting close to what I want to accomplish. The problem is that the information " south-east and 2km from city center" can lead to more than one neighborhoods.
I am still thinking that the partition of the city in neighborhoods is valuable because the socio-economic and structural differences between them ( there is a reason why the neighborhoods of each city are separated as such, right?) can lead to a higher probability for a certain category crime and a lower one for another.
That said, your idea made me thinking of using the south-east etc mapping and then use the angle of the segment(point to city center) with x axis to map the point to appropriate neighborhood. I am on it right now. Thanks
After some time on the problem I found that the procedure I want to perform is titled " reverse geocoding". It also turns out that there are some api's to solve this. The best according to my opinion is revgeocode() function contained in ggmap package(google's edition). This one though has a query limit per day(2500 queries) unless you pay for extra.
The one that I turned to though is geonames package and GNneighbourhood function that turns coordinates to neighbours. It is free, though I have experienced some errors(keep in mind that this one is only for US and Canada cities)
revgeocode function-ggmap package
Gnneighbourhood-geonames package

Find projection-datum type for coords

I try to find a way to get the projection type of the following coords.
I need to convert these coords in WGS84 latitude longitude format. I have only 1 hint: these coords are located in Florida-USA (Broward County)
<XCoordinate>9082520</XCoordinate>
<YCoordinate>6563620</YCoordinate>
Thanks
I suspect your data are in "SPC" (State Plane Coordinate) system. This is often used for "local" coordinates - it makes calculations for such things as distances and routes much easier. If that is the case, and the county in question is Broward (which is zone 0901), then there is still some guessing to do... because one can use "US feet", "International feet", or meters in this system.
If you go to http://www.earthpoint.us/Convert.aspx you can enter your coordinates in the "Position" box. Depending on what you choose you will get different answers. I suggest you try to see which makes sense (if you suspect the coordinates are for a post office and you land in a lake you probably are using the wrong number):
0901 908252.0ftE 656362.0ftN gives 26°08'14.5036", -080°13'53.8483"
That puts you pretty much on top of a bus stop - which I guess is what the Hastus system might be giving you...

Resources