I am trying to map some data in R using ggmap. When I get the map it looks something like this.
cen <- geocode('Danmark')
center <- as.numeric(cen)
map <- get_googlemap(center = center, zoom = 6,
size = c(640, 640), scale = 2, region="dk",crop = TRUE,color="bw")
ggmap(map) #+ geom_point(aes(x = lon, y = lat, size=antal), data=df, colour="darkred")
The problem is that the island of Bornholm is located to the far east of Denmark. This makes the map very large. To increase the space usage I would like to move Bornholm to the upper right corner. Something like this
How can I do this in ggmap and still overlay data?
Related
I am trying to plot a world map and a path between Berlin and Cancun.
So far I managed to plot a world map using library rnaturalearth and convert it to a ggplot2 object which is plotted using rayshader plot_gg function.
After that I tried to add a rayshader path overlay from Berlin (52.5200° N, 13.4050° E) to Cancun (21.1619° N, -86.8515° E). Here is the result:
As you can see the path is up too high and also a bit too long. My best guess right now is that it has to do something with the offset of the rayshader plot and the ggplot object (The white border around the world map).
Here is my code:
#load libraries
library(sf)
library(rayshader)
library(rayrender)
library(rnaturalearth)
library(rnaturalearthdata)
library(tidyverse)
#get ggplot object of world
world <- ne_countries(scale = "medium", returnclass = "sf")
ggData = ggplot(data = world) + geom_sf()
#latitudes, longitudes of Berlin and Cancun as list for render_path()
lats = list()
lats[1] = 52.5
lats[2] = 21.1
longs = list()
longs[1] = 13.4
longs[2] = -86.8
#Altitude of the path
alts = list()
alts[1] = 100
alts[2] = 100
#plot with rayshader, width and height ratio of bbox of ggData
plot_gg(ggData, scale=10, width=3.6, height=1.7359854)
render_path(lat = unlist(lats), long = unlist(longs), zscale=50, color="red", antialias=TRUE, linewidth=3, extent=st_bbox(world), altitude=unlist(alts))
I tried it with different width and height ratios to match the ggplot object as I thought it might have to do something with wrong aspect ratios.
One option is to render the travel path not via rayshader but include it already in your ggplot object like so (required libraries as in OP):
create feature world:
world = ne_countries(scale = "medium", returnclass = "sf")
create feature my_path (the travel path) from linestring from point coordinates:
my_path <-
c(13.4, 52.5, ## longs
-86.6, 21.1 ## lats
) |>
matrix(ncol = 2, byrow = TRUE) |>
st_linestring() |>
st_sfc() |>
st_set_crs(4326) ## set CRS to geographic (degrees)
add features world and my_path as layers to ggplot object:
ggData <-
ggplot() +
geom_sf(data = world) +
geom_sf(data = my_path, col = 'red') +
coord_sf(
## see ?coord_sf to set map limits etc.
)
plot
plot_gg(ggData)
EDITED: The original plots were for a slightly modified ggData. This post corrects things.
I don't know what the cause is, but the extent argument in your render_path() call is wrong. You can see this if you try plotting straight lines at known latitudes or longitudes. The grid lines are at latitudes -45, 0, 45 and longitudes -120, -60, 0, 60, 120. If you plot paths along those lines, the latitude paths are okay, but the longitude paths are wrong. For example, using this path:
render_path(lat = c(-45, 45), long = c(-60, -60),
zscale=50, color="red", antialias=TRUE, linewidth=3,
extent=st_bbox(world), altitude=unlist(alts))
gives this on the map:
with the path drawn too far west, and too long. If I change the extent argument using
bbox <- st_bbox(world)
bbox[c(1,3)] <- 1.2*bbox[c(1,3)]
bbox[c(2,4)] <- 1.1*bbox[c(2,4)]
it looks better. I found those numbers by trial and error; you (or someone else) will have to do some research if you want to explain them. It's still not perfect, so your path still misses Berlin and Cancun, but not by as much.
I have been trying to create a map of membership locations from postcodes across the UK as a project in learning R. I have achieved nearly the result I wanted, but it's proving very frustrating getting the glitches sorted. This image is my current best effort:
I still want to change:
get rid of the extraneous legend (the "0.16", "0.5" squares), which are coming from the size arg to geom_point. If I remove the size=0.16 arg the guide/legend disappears, but the geom size returns to the default too. This also happens for the "black" guide -- coming from a colour obviously -- but why?
properly clip the stat_density2d polygons, which are exhibiting undesireable behaviour when clipped (see bottom-right plot near the top)
have control over the line-width of the geom_path that includes the county boundaries: it's currently too thick (would like about 1/2 thickness shown) but all I can achieve by including 'size' values is to make the lines stupidly thick - so thick that they obscure the whole map.
The R code uses revgeocode() to find the placename closest to the centre point but I don't know how to include the annotation on the map. I would like to include it in a text-box over the North Sea (top right of UK maps), maybe with a line/arrow to the point itself. A simpler option could just be some text beneath the UK map, below the x-axis ... but I don't know how to do that. geom_rect/geom_text seem fraught in this context.
Finally, I wanted to export the map to a high-res image, but when I do that everything changes again, see:
which shows the high-res (~1700x1800px) image on the left and the Rstudio version (~660x720px) on the right. The proportions of the maps have changed and the geom_text and geom_point for the centre point are now tiny. I would be happy if the gap between the two map rows was always fairly small, too (rather than just small at high res).
Code
The basics: read list of members postcodes, join with mySociety table of postcode<>OSGB locations, convert locations to Lat/long with spTransform, calculate binhex and density layers, plot with ggmap.
The code for all this is somewhat lengthy so I have uploaded it as a Gist:
https://gist.github.com/rivimey/ee4ab39a6940c0092c35
but for reference the 'guts' of the mapping code is here:
# Get a stylised base map for the whole-of-uk maps.
map.bbox = c(left = -6.5, bottom = 49.5, right = 2, top = 58)
basemap.uk <- get_stamenmap(bb = map.bbox, zoom=calc_zoom(map.bbox), maptype="watercolor")
# Calculate the density plot - a continuous approximation.
smap.den <- stat_density2d(aes(x = lat, y = lon, fill = ..level.., alpha = ..level..),
data = membs.wgs84.df, geom = "polygon",
breaks=2/(1.5^seq(0,12,by=1)), na.rm = TRUE)
# Create a point on the map representing the centroid, and label it.
cmap.p <- geom_point(aes(x = clat, y = clon), show_guide = FALSE, data = centroid.df, alpha = 1)
cmap.t1 <- geom_text(aes(x = clat, y = clon+0.22, label = "Centre", size=0.16), data = centroid.df)
cmap.t2 <- geom_text(aes(x = clat, y = clon+0.1, label = "Centre", size=0.25), data = centroid.df)
# Create an alternative presentation, as binned hexagons, which is more true to the data.
smap.bin <- geom_hex(aes(x = lat, y = lon),
data = membs.wgs84.df, binwidth = c(0.15, 0.1), alpha = 0.7, na.rm = TRUE)
# Create a path for the county and country boundaries, to help identify map regions.
bounds <- geom_path(aes(x = long, y = lat, group = group, colour = "black"), show_guide = FALSE,
data = boundaries.subset, na.rm = TRUE)
# Create the first two actual maps: a whole-uk binned map, and a whole-uk density map.
map.bin <- ggmap(basemap.uk) + smap.bin + grad + cmap.p + cmap.t1
map.den <- ggmap(basemap.uk) + smap.den + alpha + cmap.p + cmap.t1
# Create a zoomed-in map for the south-east, to show greater detail. I would like to use this
# bbox but google maps don't respect it :(
map.lon.bbox = c(left = -1, bottom = 51, right = 1, top = 52)
# Get a google terrain map for the south-east, bbox roughly (-1.7,1.7, 50.1, 53)
basemap.lon <- get_map(location = c(0,51.8), zoom = 8, maptype="terrain", color = "bw")
# Create a new hexbin with more detail than earlier.
smap.lon.bin <- geom_hex(aes(x = lat, y = lon),
data = membs.wgs84.df, bins=26, alpha = 0.7, na.rm = TRUE)
# Noe create the last two maps: binned and density maps for London and the SE.
lonmap.bin <- ggmap(basemap.lon) + bounds + smap.lon.bin + grad + cmap.p + cmap.t2
lonmap.den <- ggmap(basemap.lon) + bounds + smap.den + alpha + cmap.p + cmap.t2
# Arrange the maps in 2x2 grid, and tell the grid code to let the first row be taller than the second.
multiplot(map.bin, lonmap.bin, map.den, lonmap.den, heights = unit( c(10,7), "null"), cols=2 )
I would like to create a map that is not perfectly square but rectangular and is the size I dictate.
require(ggmap)
tenmile <- get_map(location = c(lon = -122.486328, lat = 48.862813),
color = "color",
source = "google",
maptype = "roadmap",
zoom = 12)
tenmile.map <- ggmap(tenmile,
extent = "device",
ylab = "Latitude",
xlab = "Longitude")+ggtitle("GEOMean for Data from Oct 2013-Nov 2014")
tenmile.map + geom_point(data=pp, aes(x=lon, y=lat, size=geomean), color="red", alpha=0.5) +
geom_text(data=pp, aes(x=lon, y=lat, label = site), size=3, vjust = 1.25, hjust = -0.1)
I would post pictures of what I get and what I want but I do not have enough reputation points to post images. =-(
Sandy Muspratt's answer produces a rectangular map, but it gets stretched. To get an unstretched map, ratio must be adjusted to the ratio between spacing of parallels and meridians at the place of the map. That is:
ratio = 1/cos(latitude)
If latitude is given in degrees, that becomes:
ratio = 1/cos(pi*latitude/180)
I give here an example using a map of Barcelona (Barcelona makes a good example to check for stretching because most of our streets form an square grid and deformation becomes easily noticeable).
library(ggmap) library(mapproj) mapbcn <- get_map(location =
'Barcelona, Catalonia', zoom = 13)
# square map (default) ggmap(mapbcn)
# map cropped by latitude
ggmap(mapbcn) +
coord_fixed(ylim=c(41.36,41.41),
ratio=1/cos(pi*41.39/180))
# map cropped by longitude
ggmap(mapbcn) +
coord_fixed(xlim=c(2.14, 2.18),
ratio=1/cos(pi*41.39/180))
It must be noted that this way coordinates keep working for the whole map (for example to add points to the map) if the area of the map is small enough not to take in account Earth's curvature - that is, to assume that meridians are parallel in the area shown by the map. It may be inaccurate in a map spanning some hundreds of kilometres and very wrong in a continent-scale map.
If you want to keep the original limits of the bounding box but simply to change its shape, you can adjust the aspect ratio. If you want to change the limits of the bounding box, then obtain the map as before but set its limits using coord_fixed() (or coord_cartesian()). Or you can adjust both the aspect ratio and the limits of the bounding box.
tenmile <- get_map(location = c(lon = -122.486328, lat = 48.862813),
color = "color",
source = "google",
maptype = "roadmap",
zoom = 12)
tenmile.map <- ggmap(tenmile,
ylab = "Latitude",
xlab = "Longitude")+ggtitle("GEOMean for Data from Oct 2013-Nov 2014") +
coord_fixed(xlim = c(-122.55, -122.40), ratio = 2/1)
I'm currently learning something on raster layer and I could put a raster layer on a ggmap using inset_raster(). Here is a sample code below:
library(ggmap)
library(animation)
auckland <- get_map(location = "Auckland",
zoom = 14,
scale = 2, ## 1280*1280 pixels
maptype = "roadmap",
color = "color")
auckland_vis <- ggmap(ggmap = auckland)
auckland_vis
rainbow <- matrix(seq(360, 2000, length = 50 * 50), nrow = 50)
rainbow[sample(1:length(rainbow), 2400, replace = FALSE)] <- NA
rainbow.r <- raster(rainbow)
## inset_raster is used to put a raster layer on a ggmap
auckland_vis +
inset_raster(rainbow.r, xmin = attributes(auckland)$bb$ll.lon,
xmax = attributes(auckland)$bb$ur.lon,
ymin = attributes(auckland)$bb$ll.lat,
ymax = attributes(auckland)$bb$ur.lat
)
Please ignore whether the points on the map is reasonable or not. I know how to change the colour of a raster data when just using plot(). I would also like to know how to change the colour of the points in ggmap. For now the colours are always white, pink, yellow and green(what if I want the colours to be blue yellow and red). Is there a function that can specify colour just like the one in ggplot?
Thanks in advance
I have a data like this:
YEAR-STORM-DATETIME-NORTH-WEST-PRESSURE-WIND-SPEED-TRACKDATE
2011-arlene-6/28/2011 6:00-19.9-92.8-1007-30-NA-6/28/2011
2011-arlene-6/28/2011 12:00-20.3-93.1-1006-35-4-6/28/2011
2011-arlene-6/28/2011 18:00-20.7-93.5-1006-40-5-6/28/2011
so on..
I am new to R and I am plotting a density-plot over ggmap. I am also using shiny R to display them in website. The problem is the output are all non-widescreen (squared) maps. I want to have a rectangular map, like google maps provided by Openlayers or KML.
My code is :
library(ggplot2)
library(ggmap)
mydata <- read.csv("C:/R Data/Analytics/dMetrics.csv")
slice_year <- mydata[mydata$YEAR=='2009',]
map <- get_map(c(lon = -55.3632715, lat = 31.7632836), zoom = 3,
source = 'google', maptype = c("terrain"), messaging = FALSE,
color = 'color')
world <- ggmap(map) #extent = 'device'
world <- world +
stat_density2d(data = slice_year,
aes(x = WEST, y = NORTH, fill = ..level.., alpha = ..level..),
show_guide = FALSE, geom = "polygon", na.rm = TRUE) +
scale_fill_gradient(name = "Density", low = "maroon", high = "yellow",
guide = 'colorbar')
world
Please guide me through to create a widescreen resolution map, possibly a high resolution.
To save the image as widescreen, add this to the end: ggsave(file="map.pdf", width=8, height=4.5)
To open a widescreen window, add this before calling world: windows(800,450)
Edit
It looks like ggmap just doesn't support non-sqaure aspect ratios.
The documentation claims that a bounding box can be passed into the location property, but it appears to just ignore it.
scale <- 5
ratio <- 16/9
size <- c(ratio, 1) * scale
latlongCenter <- c(0, 45)
latlongBox <- c(latlongCenter - size/2, latlongCenter + size/2)
map <- get_map(location = latlongBox)
ggmap(map)
One solution would be to produce a bigger map, and then crop the piece you don't need.
But I'm still trying to figure how to produce a big, high-resolution map (the map I'm getting is 1280x1280 - that's enough for most needs, but not to print a big map). I think there's no function for that, or bots could occupy all of Google's bandwidth. A simpler solution is to get many square maps and assemble them together, but then you'll have the Google logo in all of them.
I think the only way to do that is to produce the small square maps and cut the bottom, where the logo and copyright information are. To add their logo again in the borders of the final map (cutting them differently) would give even more work...