I have a table containing all the latitudes and longitudes of some locations in a city called queryResult and I do the following:
1 - Get the Raster map of the city[Blackpool for instance]
cityMapRaster = get_map(location = 'Blackpool', zoom = 12, source = 'google', maptype = 'roadmap')
dataToShow <- ggmap(cityMapRaster) + geom_point(aes(x = Longitude, y = Latitude), data = queryResult, alpha = .5, color = "darkred", size = 1)
print(dataToShow)
and this will return the following points on the map
Now I want to draw the outer boundary [city border line] of all these latitude and longitudes similar to the following expected result
Update 1 : Providing input data and applying suggested ahull solution:
ggmap(cityMapRaster) + geom_point(aes(x = Longitude, y = Latitude), data = queryResult, alpha = .5, color = "darkred") + ahull.gg
I applied the ahull solution suggested by #spacedman and #cuttlefish44 and got the following result which is far different than the expected polygon:
You can download the .csv file containing all latitudes and longitudes from the following link : Blackpool Lat,Lon
Googles suggested area boundary looks like the following :
If you don't want a simple convex hull (and the polygon you've drawn is far from convex) then look at alpha-shapes in the alphahull package.
I wrote an example of how to get a polygon from an alpha-shape using that package and some points that make up a complex Norway boundary:
http://rpubs.com/geospacedman/alphasimple
You should be able to follow that to get a polygon for your data, and it might even be simpler now since that was a few years ago.
Here's a reproducible example of how to use chull to calculate a convex hull solution to this. I just generate some random points for queryResult, as you did not provide data.
If you prefer a concave hull boundary, then see the answer from #Spacedman
library(ggmap)
cityMapRaster = get_map(location = 'Blackpool', zoom = 12, source = 'google', maptype = 'roadmap')
extent = attr(cityMapRaster, "bb")
queryResult = data.frame(Longitude = rnorm(200, as.numeric(extent[2] + extent[4])/2, 0.01),
Latitude = rnorm(200, as.numeric(extent[1] + extent[3])/2, 0.02))
boundary = chull(as.matrix(queryResult))
ggmap(cityMapRaster) +
geom_point(aes(x = Longitude, y = Latitude),
data = queryResult, alpha = .5, color = "darkred", size = 2) +
geom_path(aes(x = Longitude, y = Latitude), data = queryResult[c(boundary, boundary[1]),])
I suppose queryResult is x and y datasets. As far as I see, your boundary isn't convex hull, so I used alphahull package.
## example `queryResult`
set.seed(1)
df <- data.frame(Longitude = runif(200, -3.05, -2.97), Latitude = rnorm(200, 53.82, 0.02))
library(alphahull)
ahull.obj <- ahull(df, alpha = 0.03)
plot(ahull.obj) # to check
# ahull_track() returns the output as a list of geom_path objs
ahull.gg <- ahull_track(df, alpha=0.03, nps = 1000)
## change graphic param
for(i in 1:length(ahull.gg)) ahull.gg[[i]]$aes_params$colour <- "green3"
ggmap(cityMapRaster) +
geom_point(aes(x = Longitude, y = Latitude), data = df, alpha = .5, color = "darkred") +
ahull.gg
## if you like not curve but linear
ashape.obj <- ashape(df, alpha = 0.015)
plot(ashape.obj) # to check
ashape.df <- as.data.frame(ashape.obj$edge[,c("x1", "x2", "y1", "y2")])
ggmap(cityMapRaster) +
geom_point(aes(x = Longitude, y = Latitude), data = df, alpha = .5, color = "darkred") +
geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = ashape.df, colour="green3", alpha=0.8)
Related
I have developed a genetic algorithm for estimating the probability of observing an animal, given its genotype, across a regular grid of locations, here in south-east England. Using ggplot2 I can easily generate either a probability contour plot or a land-only (polygon-filled) map, but what I want is a map where the contour plot is restricted to land:
()
The desired outcome is generated by adding a black mask to the contour plot in Powerpoint, a tedious procedure that is impractical for generating the hundreds I need. I am sure there must be a simple way to do this.
I generate the contour plot using:
v <- ggplot(data, aes(Lat, Lng, z = P))
v + geom_contour(bins = 20)
and the map using:
ggplot(data = world) +
geom_sf(color = "black", fill = "gray") +
coord_sf(xlim = c(-2.3, 1.9), ylim = c(50.9, 53.5), expand = FALSE)
my input file comprises all locations in 0.05 increments of longitude and latitude in the intervals specified. It is large but I would happily add it if this helps. I have looked online and cannot see any examples that match what I want.
I have tried adding one component to the other as an extra layer but I struggle to understand what is needed and what the syntax are. For example:
layer(geom = "contour", stat = "identity", data = data, mapping = aes(Lng,Lat,P))
Error: Attempted to create layer with no position.
but even if this works it does not mask the sea area.
Here's a worked example with some made-up data:
library(rnaturalearth)
library(ggplot2)
sea <- ne_download(scale = 10, type = 'ocean', category = "physical",
returnclass = "sf")
ggplot(data) +
geom_contour_filled(aes(Lng, Lat, z = P), bins = 20, color = "black") +
guides(fill = "none") +
geom_sf(data = sea, fill = "black") +
coord_sf(ylim = c(51, 53.5), xlim = c(-2.2, 1.8), expand = FALSE)
Data used
set.seed(1)
a <- MASS::kde2d(rnorm(100), rnorm(100, 53), n = 100,
lims = c(-2.2, 1.8, 51, 53.5))
b <- MASS::kde2d(rnorm(25, 0.5), rnorm(25, 52), n = 100,
lims = c(-2.2, 1.8, 51, 53.5))
a$z <- b$z - a$z + max(a$z)
data <- cbind(expand.grid(Lng = a$x, Lat = a$y), P = c(a$z))
Created on 2023-01-02 with reprex v2.0.2
I want to show 15 mile radius circles around points in a map using gBuffer. As far as I can tell I have the points and the map in the same projection, but when I produce the circles on the map, they are too large. Here is my code. The tigerline files for the state and counties can be found at https://www.census.gov/cgi-bin/geo/shapefiles/index.php.
library(tidyverse)
library(rgdal)
library(rgeos)
library(ggplot2)
state <- readOGR('C:\\Users\\Mesonet\\Desktop\\map_folder\\tl_2020_us_state\\tl_2020_us_state.shp')
state <- state[which(state$STATEFP == '46'),]
state <- spTransform(state, CRS("+init=epsg:3857"))
counties <- readOGR('C:\\Users\\Mesonet\\Desktop\\map_folder\\tl_2020_us_county\\tl_2020_us_county.shp')
counties <- counties[which(counties$STATEFP == '46'),]
counties <- spTransform(counties, CRS("+init=epsg:3857"))
sites <- data.frame(Lon = c(-98.1096,-98.27935), Lat = c(43.9029, 43.717258))
coordinates(sites) <- ~Lon + Lat
proj4string(sites) <- CRS("+proj=longlat")
sites <- spTransform(sites, CRS = CRS("+init=epsg:3857"))
# Miles to meters conversion
mile2meter <- function(x){x * 1609.344}
# Buffer creation
site_buffer <- gBuffer(sites, width = mile2meter(15))
png('C:\\Users\\Mesonet\\Desktop\\map_folder\\new_test.png', height = 3000, width = 42*100, res = 100)
ggplot() + geom_path(counties, mapping = aes(x = long, y = lat, group = group), size = 1.75,
alpha = 0.45, col = 'darkgreen') + geom_path(state, mapping = aes(x = long, y = lat, group =
group), size = 0.8) + theme(axis.text = element_blank()) + geom_polygon(site_buffer, mapping
= aes(x = long, y = lat, group = group), fill = '#0000FF', alpha = 1, size = 2)
dev.off()
These two locations are 15.35 miles apart, but the plot shows two circles that overlap each other by a couple miles. I can't figure out why, since from what I can see everything is in the same projection, but I might be wrong. Thank you.
I have a dataset like
latitude longitude Class prediction
9.7 21.757 244732 1
12.21 36.736 112206 0
-15.966 126.844 133969 1
Now i am trying to group all '1' at prediction column and take their latitude and longitude, later i want to display the all points on a single map.
Actually the code i wrote its takes each '1' on prediction column and takes lat and long respectively and display one point on map each time. But I want to collect all lat and long where prediction is 1 and display all points on a one map.
library(ggplot2)
library(ggmap) #install.packages("ggmap")
#data set name testData1
for (i in 1:100){
if (testData1$prediction[i]==1) {
lat <- testData1$latitude[i]
lon <- testData1$longitude[i]
df <- as.data.frame(cbind(lon,lat))
# getting the map
mapgilbert <- get_map(location = c(lon = mean(df$lon), lat = mean(df$lat)), zoom = 4,
maptype = "satellite", scale = 2)
# plotting the map with some points on it
ggmap(mapgilbert) +
geom_point(data = df, aes(x = lon, y = lat, fill = "red", alpha = 0.8), size = 5, shape = 21) +
guides(fill=FALSE, alpha=FALSE, size=FALSE)
}
}
I think you're overcomplicating things. You could simply subset df like so:
ggmap(mapgilbert) +
geom_point(data = subset(df, prediction == 1), aes(x = lon, y = lat, fill = "red", alpha = 0.8), size = 5, shape = 21) +
guides(fill = FALSE, alpha = FALSE, size = FALSE)
I have a map with the 8 points plotted on it:
library(ggplot2)
library(ggmap)
data = data.frame(
ID = as.numeric(c(1:8)),
longitude = as.numeric(c(-63.27462, -63.26499, -63.25658, -63.2519, -63.2311, -63.2175, -63.23623, -63.25958)),
latitude = as.numeric(c(17.6328, 17.64614, 17.64755, 17.64632, 17.64888, 17.63113, 17.61252, 17.62463))
)
island = get_map(location = c(lon = -63.247593, lat = 17.631598), zoom = 13, maptype = "satellite")
islandMap = ggmap(island, extent = "panel", legend = "bottomright")
RL = geom_point(aes(x = longitude, y = latitude), data = data, color = "#ff0000")
islandMap + RL + scale_x_continuous(limits = c(-63.280, -63.21), expand = c(0, 0)) + scale_y_continuous(limits = c(17.605, 17.66), expand = c(0, 0))
Now I want to plot a circle around each of the 8 plotted locations. The circle has to have a radius of 450 meters.
This is what I mean, but then using ggplot: https://gis.stackexchange.com/questions/119736/ggmap-create-circle-symbol-where-radius-represents-distance-miles-or-km
How can I achieve this?
If you only work on a small area of the earth, here is a approximation. Each degree of the latitude represents 40075 / 360 kilometers. Each degrees of longitude represents (40075 / 360) * cos(latitude) kilomemters. With this, we can calculate approximately a data frame including all points on circles, knowing the circle centers and radius.
library(ggplot2)
library(ggmap)
data = data.frame(
ID = as.numeric(c(1:8)),
longitude = as.numeric(c(-63.27462, -63.26499, -63.25658, -63.2519, -63.2311, -63.2175, -63.23623, -63.25958)),
latitude = as.numeric(c(17.6328, 17.64614, 17.64755, 17.64632, 17.64888, 17.63113, 17.61252, 17.62463))
)
#################################################################################
# create circles data frame from the centers data frame
make_circles <- function(centers, radius, nPoints = 100){
# centers: the data frame of centers with ID
# radius: radius measured in kilometer
#
meanLat <- mean(centers$latitude)
# length per longitude changes with lattitude, so need correction
radiusLon <- radius /111 / cos(meanLat/57.3)
radiusLat <- radius / 111
circleDF <- data.frame(ID = rep(centers$ID, each = nPoints))
angle <- seq(0,2*pi,length.out = nPoints)
circleDF$lon <- unlist(lapply(centers$longitude, function(x) x + radiusLon * cos(angle)))
circleDF$lat <- unlist(lapply(centers$latitude, function(x) x + radiusLat * sin(angle)))
return(circleDF)
}
# here is the data frame for all circles
myCircles <- make_circles(data, 0.45)
##################################################################################
island = get_map(location = c(lon = -63.247593, lat = 17.631598), zoom = 13, maptype = "satellite")
islandMap = ggmap(island, extent = "panel", legend = "bottomright")
RL = geom_point(aes(x = longitude, y = latitude), data = data, color = "#ff0000")
islandMap + RL +
scale_x_continuous(limits = c(-63.280, -63.21), expand = c(0, 0)) +
scale_y_continuous(limits = c(17.605, 17.66), expand = c(0, 0)) +
########### add circles
geom_polygon(data = myCircles, aes(lon, lat, group = ID), color = "red", alpha = 0)
Well, as the referred posting already suggests - switch to a projection that is based in meters, and then back:
library(rgeos)
library(sp)
d <- SpatialPointsDataFrame(coords = data[, -1],
data = data,
proj4string = CRS("+init=epsg:4326"))
d_mrc <- spTransform(d, CRS("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs"))
Now, the width can be specified in meters:
d_mrc_bff_mrc <- gBuffer(d_mrc, byid = TRUE, width = 450)
Transform it back and add it to the plot using geom_path:
d_mrc_bff <- spTransform(d_mrc_bff_mrc, CRS("+init=epsg:4326"))
d_mrc_bff_fort <- fortify(d_mrc_bff)
islandMap +
RL +
geom_path(data=d_mrc_bff_fort, aes(long, lat, group=group), color="red") +
scale_x_continuous(limits = c(-63.280, -63.21), expand = c(0, 0)) +
scale_y_continuous(limits = c(17.605, 17.66), expand = c(0, 0))
Calculating distance in km given latitude and longitude isn't super straightforward; 1 degree lat/long is a greater distance at the equator than at the poles, for example. If you want an easy workaround that you can eyeball for accuracy, you might try:
islandMap + RL +
scale_x_continuous(limits = c(-63.280, -63.21), expand = c(0, 0)) +
scale_y_continuous(limits = c(17.605, 17.66), expand = c(0, 0)) +
geom_point(aes(x = longitude, y = latitude), data = data, size = 20, shape = 1, color = "#ff0000")
You'll need to adjust the size paramter in the 2nd geom_point to get closer to what you want. I hope that helps!
An accurate solution is using the geosphere::destPoint() function. This works without switching projections.
Define function to determine 360 points with a certain radius around one point:
library(dplyr)
library(geosphere)
fn_circle <- function(id1, lon1, lat1, radius){
data.frame(ID = id1, degree = 1:360) %>%
rowwise() %>%
mutate(lon = destPoint(c(lon1, lat1), degree, radius)[1]) %>%
mutate(lat = destPoint(c(lon1, lat1), degree, radius)[2])
}
Apply function to each row of data and convert to data.frame:
circle <- apply(data, 1, function(x) fn_circle(x[1], x[2], x[3], 450))
circle <- do.call(rbind, circle)
Then the map can be easily obtained by:
islandMap +
RL +
scale_x_continuous(limits = c(-63.280, -63.21), expand = c(0, 0)) +
scale_y_continuous(limits = c(17.605, 17.66), expand = c(0, 0)) +
geom_polygon(data = circle, aes(lon, lat, group = ID), color = "red", alpha = 0)
A solution using st_buffer() from the sf package.
library(ggmap)
library(ggplot2)
library(sf)
data <- data.frame(
ID = 1:8,
longitude = c(-63.27462, -63.26499, -63.25658, -63.2519,
-63.2311, -63.2175, -63.23623, -63.25958),
latitude = c(17.6328, 17.64614, 17.64755, 17.64632,
17.64888, 17.63113, 17.61252, 17.62463)
)
Convert data.frame to sf object:
points_sf <- sf::st_as_sf(data, coords = c("longitude", "latitude"), crs = 4326)
For this example we use UTM zone 20, which contains the coordinates of the island:
data_sf_utm <- sf::st_transform(points_sf, "+proj=utm +zone=20")
Now we can buffer the point by 450 meters:
circle <- sf::st_buffer(data_sf_utm, dist = 450)
ggmap seems to have some issues with geom_sf. Setting inherit.aes to FALSE returns the desired map.
island <- ggmap::get_map(location = c(lon = -63.247593, lat = 17.631598), zoom = 14, maptype = "satellite")
ggmap(island, extent = "panel", legend = "bottomright") +
geom_sf(data = points_sf, color = "red", inherit.aes = FALSE) +
geom_sf(data = circle, color = "red", alpha = 0, inherit.aes = FALSE)
Created on 2020-10-11 by the reprex package (v0.3.0)
I am generating maps with world-scale data, and then zooming in to certain regions. On the zoomed-in view, I would like to show that there are other data points outside the bounding box, by putting arrowheads that point from the center of the box to where the data point is in the outside world.
Note: I do not need it to be a "great circle" path, just XY vectors in Mercator projection, because I imagine this will be useful for "normal" plots as well.
As an example, here is the world map showing the extent of the data:
And here is the zoomed in view, with magenta arrows manually added to show what I would like to generate.
Below is the code and data I am using to generate these two basic plots. What I need is a way to generate the arrowheads.
require(ggplot2)
te = structure(list(lat = c(33.7399, 32.8571, 50.2214, 36.96263, 33.5835,
33.54557, 47.76147, 48, 59.40289, 35.93411, 32.87962, 38.3241,
50.03844, 37.44, 50.07774, 50.26668, 36.5944), lng = c(-118.37608,
-117.25746, -5.3865, -122.00809, -117.86159, -117.79805, -124.45055,
-126, -146.35157, -122.931472, -117.25285, -123.07331, -5.26339,
25.4, -5.709894, -3.86828, -121.96201)), .Names = c("lat", "lng"
), class = "data.frame", row.names = c(NA, -17L))
all_states = map_data("world")
# world version:
wp = ggplot() +
geom_polygon(data = all_states, aes(x = long, y = lat, group = group), colour = "gray",
fill = "gray") +
coord_cartesian(ylim = c(0, 80), xlim = c(-155, 45)) +
geom_point(data = te, aes(x = lng, y = lat), color = "blue", size = 5,alpha = 0.6)
print(wp)
#states plot
sp = ggplot() +
geom_polygon(data = all_states, aes(x = long, y = lat, group = group), colour = "gray", fill = "gray") +
coord_cartesian(ylim = c(30, 52), xlim = c(-128, -114)) +
geom_point(data = te, aes(x = lng, y = lat), color = "blue", size = 5, alpha = 0.6)
print(sp)
This solution uses sp and rgeos packages to manipulate spatial data, the main crux being intersecting lines and a box polygon to get the edge points for arrows. Then if you draw arrows with geom_segment and zero width, the line is invisible and only the arrow head remains.
This function computes the line-box intersections:
boxint <- function(xlim, ylim, xp, yp){
## build box as SpatialPolygons
box = cbind(xlim[c(1,2,2,1,1)],
ylim[c(1,1,2,2,1)])
box <- sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(box)),ID=1)))
## get centre of box
x0=mean(xlim)
y0=mean(ylim)
## construct line segments to points
sl = sp::SpatialLines(
lapply(1:length(xp),
function(i){
sp::Lines(list(sp::Line(cbind(c(x0,xp[i]),c(y0,yp[i])))),ID=i)
}
)
)
## intersect lines segments with boxes to make points
pts = rgeos::gIntersection(sl, as(box, "SpatialLines"))
as.data.frame(sp::coordinates(pts), row.names=1:length(xp))
}
And this returns the geom with arrows:
wherelse <- function(xlim, ylim, points){
## get points outside bounding box
outsides = points[!(
points$lng>=xlim[1] &
points$lng <= xlim[2] &
points$lat >= ylim[1] &
points$lat <= ylim[2]),]
npts = nrow(outsides)
## get centre point of box
x = rep(mean(xlim),npts)
y = rep(mean(ylim),npts)
## compute box-point intersections
pts = boxint(xlim, ylim, outsides$lng, outsides$lat)
pts$x0=x
pts$y0=y
## create arrow segments as invisible lines with visible arrowheads
ggplot2::geom_segment(data=pts, aes(x=x0,y=y0,xend=x,yend=y),
lwd=0, arrow=grid::arrow(length=unit(0.5,"cm"),
type="closed"),col="magenta")
}
So your example, the basic plot is:
sp = ggplot() +
geom_polygon(
data=all_states,
aes(x=long, y=lat, group = group),colour="gray",fill="gray" ) +
coord_cartesian(ylim=c(30, 52), xlim=c(-128,-114)) +
geom_point(data=te,aes(x=lng,y=lat),color="blue",size=5,alpha=0.6)
and then add the arrows with:
sp + wherelse(c(-128,-114), c(30,52), te)
Not sure if there's an option to draw arrows exactly like you want them though!
Here is my attempt. This is the closest I got. I used gcIntermediate() for calculating the shortest distance between the center point of your US map and the data points which stay outside of the bbox. Hence, the arrow positions may not be something you want. My hope is that somebody else would deliver a better solution based on this attempt.
I first arranged your df (i.e., te) with the center point in the US zoomed map. I then chose data points which are not in the bbox of the US map. Then, add two columns to indicate the center point of the US map. Rename two columns and calculate the shortest distance with gcIntermediate.
library(dplyr)
library(ggplot2)
library(geosphere)
filter(te, !between(lng, -128, -114) | !between(lat, 30, 52)) %>%
mutate(start_long = (-128 - 114) / 2,
start_lat = (30 + 52) / 2) %>%
rename(end_lat = lat, end_long = lng) %>%
do(fortify(as(gcIntermediate(.[,c("start_long", "start_lat")],
.[,c("end_long", "end_lat")],
100,
breakAtDateLine = FALSE,
addStartEnd = TRUE,
sp = TRUE), "SpatialLinesDataFrame"))) -> foo
foo contains 100 data points to draw respective line. I chose data points which stay close to the bbox boundary. I was specifically looking for two data points for each line so that I could use geom_segment() later. I admit that I played with the filter condition a bit. In the end, I did not subset data using lat in this case.
filter(foo, between(long, -128, -126.5) | between(long, -115.5, -114)) %>%
group_by(group) %>%
slice(c(1,n())) -> mydf
In the next step, I rearranged the data frame based on this link
mutate(mydf, end_long = lag(long), end_lat = lag(lat)) %>%
slice(n()) -> mydf2
Finally I drew the map with arrows. I hope this will provide some kind of base for you. I also hope that other SO users will provide better solutions.
ggplot() +
geom_polygon(data = all_states, aes(x = long, y = lat, group = group),
colour = "gray", fill = "gray" ) +
coord_cartesian(ylim = c(30, 52), xlim = c(-128,-114)) +
geom_point(data = te, aes(x = lng,y = lat), color = "blue", size = 5,alpha = 0.6) +
geom_segment(data = mydf2, aes(x = end_long, xend = long,
y = end_lat, yend = lat, group = group),
arrow = arrow(length = unit(0.2, "cm"), ends = "last"))