Hot answers tagged

12

Robin Lovelace has provided a nice little function to download a ggmap object and convert it to a raster. Using this you could do: library(ggmap) library(raster) library(rgdal) # courtesy R Lovelace ggmap_rast <- function(map){ map_bbox <- attr(map, 'bb') .extent <- extent(as.numeric(map_bbox[c(2,4,1,3)])) my_map <- raster(.extent, nrow= ...


11

Get the bounds of Denmark in lat-long and use coord_fixed: ggplot() + borders("world", colour="gray50", fill="gray50") + coord_fixed(xlim=c(7, 12), ylim=c(52, 58)) You can get the bounds from the map package: > map("world", "Denmark", plot=FALSE)$range [1] 8.121484 15.137110 54.628857 57.736916 And you might want to expand these a bit for nicer ...


9

as.data.frame() does not work for SpatialPolgons in geom_polygon, because the geometry gets lost. You have to use ggplot2::fortify (may be deprecated in the future, see ?fortify). The recommended way is now to use broom::tidy: R> library("broom") R> head(tidy(kommune)) Regions defined for each Polygons long lat order hole piece group id 1 10.29 ...


8

Try the reproducible example below. You need to use Spatial objects. # Load libraries library('ggmap') library('sp') library('rgeos') library('mapview') # Interactive maps in R # Grab a route from Google route_df <- route(from = "Cambridge, 02138, USA", to = "Massachusetts Ave, 02139, USA", mode = "driving", structure ...


8

You can now do this directly with the ggalt package: library(ggplot2) library(ggalt) library(ggthemes) wrld <- map_data("world") gg <- ggplot() gg <- gg + geom_map(data=wrld, map=wrld, aes(x=long, y=lat, map_id=region), color="#2b2b2b", size=0.15, fill=NA) gg <- gg + coord_proj("+proj=robin +lon_0=0 +x_0=...


7

The actual problem is to plot a circle with 40 miles in diameter on a map with a lat/lon projection (typically EPSG:4326), because native map units are degrees. Therefore, it seems to me the simplest solution is to work with a different projection that is based on meters (that can easily be converted to miles) rather than degrees. As an alternative to ...


6

Here is a suggestion. I create the circles with gBuffer and then reproject them into WGS84 for ggmap. To change the colors of the heat map use scale_fill_gradient(). library(ggmap) library(sp) library(rgdal) library(rgeos) # get the NY coordinates nyc <- geocode("New York") # create spatialPoint object coordinates(nyc) <- ~ lon + lat proj4string(...


5

I have figured out how to do this. I checked the code for get_map and all it does is download the .png file and use readPNG() method to read it back in. Therefore I was able to manually do the downloading part (using the URL from get_map) to avoid my firewall issues and use readPNG() to read the saved file into R and obtain the ggmap object.


5

Have you read the help for tm_shape? It gives the following parameter: bbox: bounding box. One of the following: • A bounding box (an ‘sf’ bbox object, see ‘st_bbox’, a 2 by 2 matrix (used by the ‘sp’ package), or an ‘Extent’ object used by the ‘raster’ package). Its in map units rather than lat-long, so with the World data ...


5

Converting the data to an sf object, you can either use ggplot as the answer before or ggmap in the following way: library(sp) library(sf) #> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3 library(dplyr, warn.conflicts = F) library(ggmap, quietly = T) data('meuse') coordinates(meuse) <- ~x+y proj4string(meuse) <- CRS("+init=epsg:28992") meuse <-...


3

This can also be done with tmap. Have a look at the tmap vignette, especially the Plotting with tmap elements section. In your case your code ought to look basically like this: tm_shape(shapefile_with_electricity_data) + tm_fill("Electricity_in_Schools_variable") + tm_shape(shapefile_with_MNO_data) + tm_dots("MNO_variable")


3

Try clipping the polygons before using them (also, please try to provide complete code including library calls in the future): library(ggmap) library(rgdal) library(rgeos) library(ggplot2) URL <- 'https://ago-item-storage.s3.amazonaws.com/f7f805eb65eb4ab787a0a3e1116ca7e5/states_21basic.zip?AWSAccessKeyId=AKIAJLEZ6UDU5TV4KMBQ&Expires=1454295860&...


3

Use functions from the sp and rgdal packages. Assuming your shape file is named myshp library(sp) library(rgdal) proj4string(myshp) # Gives the CRS of the data myshp=spTransform(myshp,CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")) # To convert it to WGS84 ggplot2 input has to be a DataFrame, to convert a SpatialDataFrame to a DataFrame named ...


3

The openmap() function expects geographic lat/lon coordinates as input. If the data you want to layer on top of such a basemap are not in WGS84, you need to reproject in order to retrieve the appropriate tiles. So the steps are: reproject your data to WGS84, retrieve the basemap using geographic coordinates, reproject the basemap to your desired ...


3

Did you save the corresponding R object as well? E.g.: # Download and save map image and R object library(ggmap) egy.map <- get_map(location=c(lon=30, lat=26), zoom=6, maptype="terrain", filename="~/Desktop/ggmapTemp") save(egy.map, file="~/Desktop/egy-map.rda") # Restart R or RStudio before running the code below library(ggmap) load("~/Desktop/egy-map....


3

For threshold: plot(v[v$copper>31,], pch = 2, col="blue") points(v[v$copper<=31,], pch = 6, col="red") For proportional: plot(v, cex=(3*(v$copper)/max(v$copper)), pch=16) Apologies; ggplot for shape: v@data$threshold = ifelse(v$copper > 31, "a", "b") ggplot(data=v@data, aes(x=x,y=y, shape = threshold)) + geom_point() + ...


2

As it turns out, the solution is to group on the region id. I think I knew this once, but hopefully this can save someone else some Google time. ggmap(OhioMap) + geom_polygon(aes(x=long, y=lat, group=group), fill = 'grey', alpha=0.4, color = 'black', data = Counties.fort)


2

I found the solution a couple of seconds ago, it had to do with the column order.I changed the numbers into a decreasing sequence (first these were completely mixed). Now I get the correct output.


2

You can aggregate the polygons and then disaggregate to the 182 individual islands. URL <- "https://osm2.cartodb.com/api/v2/sql?filename=public.galapagos_islands&q=select+*+from+public.galapagos_islands&format=geojson&bounds=&api_key=" fil <- "gal.json" if (!file.exists(fil)) download.file(URL, fil) library(rgdal) gal <- readOGR(...


2

I assume that the 'lines' you are referring to are simply the polygon boundaries separating one feature from another. If you just want to display the data and you do not necessarily have to stick with ggplot2, a possible option would be to use spplot. Just create a plot of the non-unified polygons with "transparent" line color (see ?sp.polygons) and add the ...


2

To add to the answer above: For those following their excellent tutorial/answer and wondering how to solve the next problem about the polygon clipping (as I was!) Here's the answer, courtesy of the user 'streamlinedmethod' at https://stackoverflow.com/questions/13982773/crop-for-spatialpolygonsdataframe library(maptools) library(raster) ## To convert an ...


2

Sample code. Given a world map (e.g. lat: 80 ~ -80, lon: -160 ~ 160) was downloaded as PNG ("Downloaded_Image.png"). library(png) Downloaded_Image <- readPNG("Downloaded_Image.png") library(ggplot2) ggplot(data= data, aes(x= lon, y= lat)) + annotation_raster(Downloaded_Image, xmin= -160, xmax= 160, ymin= 80, ymax= -80, ...


2

For example: library(ggplot2) ggplot(dfexp, aes(lon, lat)) + borders() + xlim(c(144.325, 144.40)) + ylim(c(-41.575, -41.5)) + stat_density_2d(aes(fill = ..level..), geom="polygon") + geom_point(position="jitter", alpha=.2, colour="white") Or using ggmap (as requested): library(ggplot2) library(ggmap) map <- get_map(make_bbox(c(144.325, 144....


2

One thing, you can't use downtown.df[downtown$slug="downtown",] because dim(downtown) != dim(downtown.df). You need to select before fortify. Also, shapefile came in NAD 83, so you need to reproject it: downtown <- spTransform(downtown, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ') downtown@data$id <- rownames(downtown@data) downtown <- ...


2

maybe something like this. Always check the order of the xmin,xmax,ymin,ymax arguments. These routinly change across different packages & objects filepathtodem <- "C:/Users/...../mydem.tif" # Change for your computer # Load libraries library(raster) library(sp) # Load your DEM r <- raster(filepathtodem) # Check projection of your raster ...


2

Okidokey. So - it turns out that even though ggmap2 can manage SpatialDataFrames, assigning values to it is pretty tricky. The issue I was having is a mismatch between each element of the polygon (so for a simple rectangular poly, there'd be 4 points), and the values associated with it. Fortifying the data as suggested by @Spacedman yields a basic data ...


2

Here is a pretty straight rewrite of https://github.com/mapbox/mercantile/blob/478e7e1c2291c828e52c381052f108ecec89989b/mercantile/init.py#L390 quadkey_to_tile = function(qk){ if(nchar(qk)==0){ return(list(x=0,y=0,zoom=0)) } xtile = 0 ytile = 0 digits = rev(strsplit(qk,"")[[1]]) for(i in 1:length(digits)){ digit = ...


2

I've repeated your example and I wonder why do you need to add additional scale properties? Everything works fine ever without additional scale settings. As far as I understand you are getting this error message because your y values are below zero (because your object is located in the Southern Hemisphere). Moreover you're trying to control a continuous ...


2

The expansion is done because of the coord_sf() parameter expand = TRUE. Setting it to FALSE should remove the "buffer". Here's the corresponding part of the documentation. ggplot() + geom_point(data= basemap.df, aes(x=x, y=y,col=rgb(layer.1/255, layer.2/255, layer.3/255))) + scale_color_identity() + geom_sf(data=state, color= &...


Only top voted, non community-wiki answers of a minimum length are eligible