ggmap and plot shows different zone on map - r

With help of ggmap and plot I want to show the centers of states on the map. The result should be something like this
I tried this block of code but is doesnt show above map
data(state)
cen_df <- as.data.frame(state.center)
library(ggmap)
library(ggplot2)
d <- data.frame(lat = cen_df[2],
lon = cen_df[1])
US <- get_map("united states", zoom = 12)
p <- ggmap(US)
p + geom_point(data = d, aes(x = lon, y = lat), color = "red", size = 30, alpha = 0.5)
ggplot_build(p)
But it shows something lie this:
Any help?

I modified your code as follows. The zoom should be 4. It is also better to use base_layer argument to put your ggplot2 object.
data(state)
library(ggmap)
library(ggplot2)
d <- data.frame(lat = state.center$y,
lon = state.center$x)
US <- get_map("united states", zoom = 4)
p <- ggmap(US, base_layer = ggplot(data = d)) +
geom_point(aes(x = lon, y = lat), color = "red", size = 2, alpha = 0.5)
p

Related

Using gBuffer from rgeos with correct projection

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.

Create shaded polygons around points with ggplot2

I saw yesterday this beautiful map of McDonalds restaurants in USA. I wanted to replicate it for France (I found some data that can be downloaded here).
I have no problem plotting the dots:
library(readxl)
library(ggplot2)
library(raster)
#open data
mac_do_FR <- read_excel("./mcdo_france.xlsx")
mac_do_FR_df <- as.data.frame(mac_do_FR)
#get a map of France
mapaFR <- getData("GADM", country="France", level=0)
#plot dots on the map
ggplot() +
geom_polygon(data = mapaFR, aes(x = long, y = lat, group = group),
fill = "transparent", size = 0.1, color="black") +
geom_point(data = mac_do_FR_df, aes(x = lon, y = lat),
colour = "orange", size = 1)
I tried several methods (Thiessen polygons, heat maps, buffers), but the results I get are very poor. I can't figure out how the shaded polygons were plotted on the American map. Any pointers?
Here's my result, but it did take some manual data wrangling.
Step 1: Get geospatial data.
library(sp)
# generate a map of France, along with a fortified dataframe version for ease of
# referencing lat / long ranges
mapaFR <- raster::getData("GADM", country="France", level=0)
map.FR <- fortify(mapaFR)
# generate a spatial point version of the same map, defining your own grid size
# (a smaller size yields a higher resolution heatmap in the final product, but will
# take longer to calculate)
grid.size = 0.01
points.FR <- expand.grid(
x = seq(min(map.FR$long), max(map.FR$long), by = grid.size),
y = seq(min(map.FR$lat), max(map.FR$lat), by = grid.size)
)
points.FR <- SpatialPoints(coords = points.FR, proj4string = mapaFR#proj4string)
Step 2: Generate a voronoi diagram based on store locations, & obtain the corresponding polygons as a SpatialPolygonsDataFrame object.
library(deldir)
library(dplyr)
voronoi.tiles <- deldir(mac_do_FR_df$lon, mac_do_FR_df$lat,
rw = c(min(map.FR$long), max(map.FR$long),
min(map.FR$lat), max(map.FR$lat)))
voronoi.tiles <- tile.list(voronoi.tiles)
voronoi.center <- lapply(voronoi.tiles,
function(l) data.frame(x.center = l$pt[1],
y.center = l$pt[2],
ptNum = l$ptNum)) %>%
data.table::rbindlist()
voronoi.polygons <- lapply(voronoi.tiles,
function(l) Polygon(coords = matrix(c(l$x, l$y),
ncol = 2),
hole = FALSE) %>%
list() %>%
Polygons(ID = l$ptNum)) %>%
SpatialPolygons(proj4string = mapaFR#proj4string) %>%
SpatialPolygonsDataFrame(data = voronoi.center,
match.ID = "ptNum")
rm(voronoi.tiles, voronoi.center)
Step 3. Check which voronoi polygon each point on the map overlaps with, & calculate its distance to the corresponding nearest store.
which.voronoi <- over(points.FR, voronoi.polygons)
points.FR <- cbind(as.data.frame(points.FR), which.voronoi)
rm(which.voronoi)
points.FR <- points.FR %>%
rowwise() %>%
mutate(dist = geosphere::distm(x = c(x, y), y = c(x.center, y.center))) %>%
ungroup() %>%
mutate(dist = ifelse(is.na(dist), max(dist, na.rm = TRUE), dist)) %>%
mutate(dist = dist / 1000) # convert from m to km for easier reading
Step 4. Plot, adjusting the fill gradient parameters as needed. I felt the result of a square root transformation looks quite good for emphasizing distances close to a store, while a log transformation is rather too exaggerated, but your mileage may vary.
ggplot() +
geom_raster(data = points.FR %>%
mutate(dist = pmin(dist, 100)),
aes(x = x, y = y, fill = dist)) +
# optional. shows outline of France for reference
geom_polygon(data = map.FR,
aes(x = long, y = lat, group = group),
fill = NA, colour = "white") +
# define colour range, mid point, & transformation (if desired) for fill
scale_fill_gradient2(low = "yellow", mid = "red", high = "black",
midpoint = 4, trans = "sqrt") +
labs(x = "longitude",
y = "latitude",
fill = "Distance in km") +
coord_quickmap()

Display all latitude and longitude once in a MAP

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)

R - Labels geom_point()

All,
Please see below code to a R script. I am simply trying to populate a map of UK with list of stores (storeLocations) and customers (CustomerLocations).
STRTRADECODE is the column name within StoreLocations table which contains name of a particular store.
I am unable to output the labels. Please help.
Thanks in advance.
library(RgoogleMaps)
library(maps)
library(ggmap)
library(ggplot)
UKMap <- qmap("United Kingdom", zoom = 6.0)
storeOverlay <- geom_point(aes(x = longitude, y = latitude),
data = StoreLocations, colour = "red")
storeOverlay <- storeOverlay + geom_text(data= StoreLocations, aes(label=STRTRADECODE))
CustomerOverlay <- geom_point(aes(x = longitude, y = latitude),
data = CustomerLocations, colour = "green")
UKMap + CustomerOverlay + storeOverlay
As I said in my commentary before, you have to add the lon and lat to geom_text, so ggplot knows, where to put the text.
Here is a working example (I included nudge_x, so the Text/Label is not directly on the point)
library(RgoogleMaps)
library(maps)
library(ggmap)
library(ggplot)
STRTRADECODE <- c("London","Sheffield","Glasgow")
StoreLocations <- as.data.frame(STRTRADECODE,stringsAsFactors=F)
StoreLocations %>%
mutate_geocode(STRTRADECODE) %>%
rename(longitude = lon,latitude=lat) -> StoreLocations
CustomerLocations <- StoreLocations
CustomerLocations$longitude <- CustomerLocations$longitude - 1
UKMap <- qmap("United Kingdom", zoom = 6.0)
UKMap +
geom_point(mapping=aes(x = longitude,
y = latitude),
data = StoreLocations,
colour = "red"
) +
geom_text(
mapping=aes(x = longitude,
y = latitude,
label = STRTRADECODE
),
data= StoreLocations,
nudge_x = 0.8
) +
geom_point(aes(x = longitude,
y = latitude
),
data = CustomerLocations,
colour = "green"
)

Multiple Points on Map

I want to plot a map with some points on it. I tried this code:
lon <- c(103.25,103.28)
lat <- c(3.80, 3.78)
df <- as.data.frame(cbind(lon,lat))
Getting the map:
mapgilbert <- get_map(location = c(lon = mean(df$lon), lat = mean(df$lat)), zoom = 12,maptype = "satellite", scale = 3)
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)
Based on this code, the same color of points appear. My question is, I want to create multiple color of points on the map. Kindly assist, your help is highly appreciated. Thank you.
You need to add a categorical variable (what should the colors express?) to govern the color aesthetics:
#create some dummy data
df$coloringCategory <- rep(c("A","B"),length(df$lat)/2)
#in ggplot include the categorical variable
geom_point(data = df, aes(x = lon, y = lat, color= coloringCategory, alpha = 0.8),size = 5, shape = 21)

Resources