GGplot geom_map gets distorted when plotting interactively with ggplotly - r

I am trying to create an interactive map of Germany with plotly and ggplot. At last, I'd like to overlay geom_points with tooltips, but so far I am struggeling with the aspect ratio.
I create the plot like this:
library(tidyverse)
library(ggplot2)
library(plotly)
p <- map_data("world") %>%
filter(region=="Germany") %>%
ggplot(aes(x=long, y = lat, group = group)) +
geom_polygon(fill="grey") +
coord_map()
When simply plotting it with ggplot, the aspect ratio of Germany is how I know it from school.
p
When converting it to a plotly plot with ggplotly the plot is distorted.
ggplotly(p)
Any ideas how to fix it? I don't know whether this is relevant, but I used to run this code in an R Markdown document.
Thanks a lot.

I'll guess you can't get a decent level of detail from the world map you used. With maps there are basically two types: generic, and, GIS (real mapping data).
Below is a non-distorted map of Germany. Here are the steps and data sources.
Download the GIS data - map of Germany. Source, https://gadm.org/download_country_v3.html
Choose the level of detail. 0 - the outline of the country, 1 - the country w/states. These files will have, sp.rds , extensions.
Cut and Paste the downloaded geographical reference data file into your working directory - this is easier than creating a path from the working directory to some other folder location. Since this data is actual geospatial data used in creating this plot of Germany, this data/plot can be used as a base map or overlay map with google maps, Overstreet maps, etc..
Use the following libraries and two lines of code to create the plot of Germany.
library(maptools)
library(raster)
library(rgdal)
gadm <- readRDS("gadm36_DEU_0_sp.rds") # get the gis file from w/d.
plot(gadm)

Related

How to draw a state map using R

I need help on how to use R to draw a map. I have created an excel csv file with latitude and longitude of counties at the boundaries of the state I want to draw. However, I don’t know the right codes in R to use and get the map drawn.
#R #Maps #howtodrawmapsinR #ggplot2 #Rmapcodes
As simple as:
library(maps)
map('county', 'iowa', fill = TRUE, col = palette())
If you like to use the data from your .csv file, then please have a look on sf and sp libraries and get familiar with creating simple geometries, like SpatialPolygons.

Plot points on map R maps package

I have a dataset of all powerplants and I've got their locations down to the format the maps package in R likes c("arkansas,clay", "arkansas,conway", ...).
Some counties have more than one powerplant, and there are 7+ types of powerplants, so I'd like to plot them as points on a map and not just color the counties, as I can see the maps package mainly doing. Was thinking to jitter their position a bit. But I don't know how to go from state/county name to location, or plot straight up points in the maps package.
Does anyone have any suggestions?
So I couldn't figure out how to do it with the maps package, but with ggplot, it's almost trivial. The first few lines of this answer made it really easy to construct a plot I needed.
Plotting bar charts on map using ggplot2?
One trick I did use was to create R's version of a hastable from the map_data in ggplot2.
usaMap=maps_data("county")
usaMap$locCode=paste(usaMap$region,",",usaMap$subregion,sep="")
usaMap2 = usaMap[!duplicated(usaMap$locCode),]
row.names(usaMap2)=usaMap2$locCode
currentGen$long = usaMap2[currentGen$locCode,"long"]+rnorm(nrow(currentGen),0,.05)
currentGen$lat = usaMap2[currentGen$locCode,"lat"]+rnorm(nrow(currentGen),0,.05)
where currentGen is my powerplants data frame and the format of the region matches exactly the format of usaMap$locCode.

Overlaying shapefiles or raster over interactive maps

I'm using R, and I want to overlay some raster data (e.g. a temperature map from a model) over an interactive map which allows panning and zooming. Ideally, I'd like to overlay over Google Maps or OpenStreetMaps. The input data can be in shapefiles, KML, raster data or whatever comes in handy.
I know I can easily do this non-interactively using either googleVis, ggmap or RgoogleMaps. But I do not want to use tiles, I want interaction! Zooming, panning etc., directly from the browser.
googleVis, as far as I know, unfortunately only allows to show interactively points or addresses, not areas.
This question is very similar but I definitely want to try to do this using R. I can create the KML or geoJSON from R, but how do I overlay it from R directly?
OpenStreetMaps is also fine, however I've not found any reference on how to overlay data over it from R, despite the fact that OSM seems to have a pretty straightforward API.
The mapview package has been developed for this particular purpose. It also comes with a variety of background map layers. For a short introduction to what mapview is capable of, feel free to browse the package vignette. Here, for example, is some code that displays locations of selected breweries in Franconian Switzerland overlaid by a sample Landsat 8 scene (band 10). Check out ?breweries91 and ?poppendorf to retrieve information about the data used below and ?mapview to grow familiar with the numerous costumization options.
## require package
# install.packages("mapview")
library(mapview)
## visualize breweries and add landsat 8 band 10
mapview(breweries91) +
poppendorf[[10]]
The leaflet package may be of interest for you. You can easily add a raster object. From the documentation
Two-dimensional RasterLayer objects (from the raster package) can be
turned into images and added to Leaflet maps using the addRasterImage
function.
And here is an example also from the documentation:
library(leaflet)
library(raster)
r <- raster("nc/oisst-sst.nc")
pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r),
na.color = "transparent")
leaflet() %>% addTiles() %>%
addRasterImage(r, colors = pal, opacity = 0.8) %>%
addLegend(pal = pal, values = values(r),
title = "Surface temp")

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

R: world maps with ggplot2/ggmap - How to load a png image as a map

I am trying to find a workaround for ggmap's missing support of world maps (i.e. you can't create any maps that show latitudes > 80°, due to idiosyncrasies in the mapproj package).
To a limited extend however, it seems possible to create empty world maps and save them as an image (png etc.), even if you can't use the ggmap object directly as one normally would in ggmap(get_map(...)).
That's why I'd like to load a png (ideally, one I created with ggmap) into ggplot2 and use that as a map instead. How exactly can I do that?
I am aware that you can load background images in ggplot2 (see this stackoverflow question). But I'd also like to plot points on my map - it's important that the latitude/longitude values are mapped correctly.
(Notice: The code in this answer to World map with ggmap provides some code that, in terms of the output, comes close to what I had in mind.)
Here is an example without ggmap that you can use.
require(ggplot2)
require(cshapes)
world <- cshp(date=as.Date("2012-01-1"))
world.points <- fortify(world, region='COWCODE')
world.points2 <- merge(world.points,world#data,by.x="id",by.y="COWCODE",all.x=TRUE )
# Add a variable 'size' per country
world.points2$size <- factor(ifelse(world.points2$AREA < 121600,"small",ifelse(world.points2$AREA > 515000, "large", "medium")))
# Coord_fixed fixes the aspect ratio.
p <- ggplot(world.points2,aes(long,lat,group=group,fill=size)) + geom_polygon(colour="grey50") + coord_fixed()
p

Resources