Choropleth maps (plotly) with detailed borders - r

I am trying to plot a world map, where the colors correspond to a specific variable. However, it does not show small states like "Andorra" or "Liechtenstein", even though they are in the data frame (see df$COUNTRY). I think the problem is, that the borders are not drawn with much detail. Hence one can not see the small states. Is there a way draw the borders with more detail like with the packs, maps, and mapdata (e.g wolrd_detailed <- map_data ("worldHires")? Or any other way to make the small states visible? Here is the example from the plotly website. It does not show small states:
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv")
fig <- plot_ly(df, type='choropleth', locations=df$CODE, z=df$GDP..BILLIONS., text=df$COUNTRY, colorscale="Blues")
fig
Thanks for the help!

Related

GGplot geom_map gets distorted when plotting interactively with ggplotly

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)

R: cropping/zooming a map

I am trying to overlay data on top of a map of Canada, however I can't adjust the zoom as I would like. In the map, I want to be able to see the lines for each province anong with its name (so using map("world", "Canada") isn't desirable)
I have tried altering the zoom, but one is too zoomed out and the other is too zoomed in:
qmap(location = "Canada", zoom = 3)
qmap(location = "Canada", zoom = 4)
I have tried researching on how to crop the image but have been unsuccessful
Thank you!
You can approach this using either the maps and mapsdata packages or continue with ggmap. It just depends on how much detail you want.
library(raster)
library(maps)
library(mapdata)
canada<-getData("GADM",country="CAN",level=1)
plot(canada,xlim=c(-141,-53),ylim=c(40,85),col="gray80",border="gray40",axes=T,las=1)
invisible(text(getSpPPolygonsLabptSlots(canada),labels=as.character(substr(canada$HASC_1,4,5)),
cex=0.75, col="black",font=2))
Using ggmap, you can specify a bounding box when grabbing your spatial data. It still overplots some of the area you are interested in (i.e., plots most of the US). Therefore, reapplying the bounding box values to the ggmap function cuts down the viewable area.
library(ggmap)
lats<-c(40,85)
lons<-c(-141,-53)
bb<-make_bbox(lon=lons,lat=lats,f=0.05)
cda<-get_map(bb,zoom=3,maptype="terrain")
ggmap(cda)+xlim(lons)+ylim(lats)+theme_bw()+labs(x="Longitude",y="Latitude")

Leaflet Polylines do not show up

I have a very small SpatialLinesDataFrame which I need to plot with Leaflet in R.
Unfortunately, for some reason I'm not able to do so.
This is the data (it's 12KB).
I try to do:
library(leaflet)
load("mylines.Rdata")
leaflet() %>% addTiles() %>% addPolylines(data=mylines)
However the resulting map does not make sense, I can only see a line in the top of the screen and this is not what should be plotted.
This is the result:
Instead, If I do:
library(mapview)
mapview(mylines)
Result:
It works perfectly, despite mapview using leaflet underneath.
What am I doing wrong in the Leaflet syntax?
I am used to working with leaflet providing rasters, so I usually use the addRasterImage function, which needs data projected over leaflet's display projection (EPSG:3857). However, for polygons and lines, as #TimSalabim correctly pointed out, this is not the case.
So the solution in this case was to just not reproject the data to the leaflet projection beforehand, and provide it in lat-lon coordinates (EPSG:4326).
mapview worked since it does this automagically.

shade between two latitudes on country map

I want to plot a simple outline of a country map and have an area between two latitudes shaded grey.
I think I need to use the rworldmap library but I'm not exactly sure how to achieve what I want.
Good suggestions by others. I initially thought that you might want the latitudinal shading to extend beyond the country borders. If that's the case here's a quick and dirty solution using rworldmap for the map, sp to plot it and polygon from base graphics to add the latitude shading. You could then modify using spTransform from rgdal if you want to project, or the suggestion from Sam if you want to crop to country borders.
library(rworldmap)
library(sp)
sPDFworld <- getMap(resolution="low")
#getMap() maps have ADMIN & NAME fields with country names formatted differently
#use sPDFworld$ADMIN sPDFworld$NAME to check
country <- "United Kingdom"
#to plot just this country (uses sp)
plot(sPDFworld[ sPDFworld$ADMIN==country, ] )
#shade a latitude region
polygon(x=c(-180,-180,180,180),y=c(55,60,60,55),col=adjustcolor('grey',alpha.f=0.5),border=NA)
I'd do something as in https://stackoverflow.com/a/13986029/1358308 . You can crop down to your "rectangle" as needed and then just plot the interiour of the resulting polygon as "grey", and don't print the borders by setting them to NA.
If you plot this "after" the larger outline (using the same polygon, before doing the intersection) then you should just get the country filled in. If you want the "water" filled in using a different color, you can do this "first". The later plot(x, add=TRUE) will plot the new things "on top" so you won't see the working behind.
Hope that makes sense!

how to plot a part of map but with limitation arround it

how to plot something like this:
see image here, I didn't have 10 reputation so I can not post image, so paste a image URL here.
http://www.flickr.com/photos/97751721#N07/9089566951
or
http://www.flickr.com/photos/97751721#N07/9091786734
right part of this map is a zoom in map with limitation, that is what I want
if it is use R code or other program language will be more great!
If your have everything as Spatial object you could simply plot with standard plot() and set lim to what ever you like.
require(maptools)
shape <- readShapePoints("shapefile.shp")
plot(shape, xlim=c(minXcoordinate, maxXcoordinate) ylim=c(minYcoordinate, maxYcoordinate))
It is a little unclear to me what exactly you want to do. Do you just want to make a map with a specific set of lon/lat boundaries? Do you need to plot data on top of it? Do you need to control the appearance to make it look like the example you give (with line boundaries & minimal geographic information)?
The ggmap package may get you started on this. The syntax goes like this:
require(ggmap)
# The location argument defines the center of the map
exampleMap <- get_map(location = c(lon = -95, lat = 30), zoom=5)
ggmap(exampleMap)
You can then add data to the map if you like (exactly how is left as an exercise to the motivated student!)

Resources