I am quite new to using R - and i am currently trying to create an elevation diagram of a study site using the below code:
library(rnaturalearth)
library(rnaturalearthhires)
library(mapview)
library(mapedit)
library(elevatr)
library(tidyverse)
library(raster)
countries<-ne_countries(scale = 110, type = "countries", continent = NULL,
country = NULL, geounit = NULL, sovereignty = NULL,
returnclass = c("sf"))
admin<-ne_states(country = NULL, geounit = NULL, iso_a2 = NULL, spdf = NULL,
returnclass = c("sf"))
admin %>% filter(name=="Áncash") -> Áncash
countries %>% filter(name=="Peru") -> PER
mapview(Áncash) %>% editMap() -> d
poly<-d$drawn
elev1 <- get_elev_raster(poly, z = 14,clip="bbox")
When I try to run this I run into the following error message:
Listening on http://my IP:8888 # For reasons I am not releasing my IP
createTcpServer: address not available
Error in .subset2(public_bind_env, "initialize")(...) :
Failed to create server
>
> poly<-d$drawn
Error: object 'd' not found
> elev1 <- get_elev_raster(poly, z = 14,clip="bbox")
Error in if (attributes(class(locations)) %in% c("raster", "sp")) { :
argument is of length zero
There is probably something really simple I am missing, but after a couple of hours trying to do this on my own, I am at the point now of needing help!
Thanks in advance!
Your code actually worked for me (eventually), once I had downloaded all the R packages which were required to run it:
library(rnaturalearth)
library(rnaturalearthhires)
library(mapview)
library(mapedit)
library(elevatr)
library(tidyverse)
library(raster)
You seem to be getting an error when running editMap, which launches a shiny application that allows you to draw lines and polygons on a map. You have witheld your IP address in your question, but this IP address should be your home address, i.e. http://127.0.0.1.
I think you might just need to change the port that shiny is running on, so try this:
options(shiny.port = 7775)
Then when you do
mapview(Áncash) %>% editMap() -> d
It should say
#> Listening on http://127.0.0.1:7775
And your viewer should show this:
You should then be able to draw a polygon on your map. I would advise that you only draw a tiny polygon, otherwise the elevation data will literally take hours to download.
When you are happy with the polygon, stop the application and d will contain your polygon. So now when you do
poly<-d$drawn
elev1 <- get_elev_raster(poly, z = 14, clip="bbox")
The data will download to the raster elev1 which you can now plot:
plot(elev1)
Related
I was wondering if it's possible to use the locator() function to create new points with plots generated by plot.sf. I'm sorry but I don't know how to create a reproducible example, so I will do my best to explain my problem.
When I run the following code (clicking, for example, on the centroid of some non-blue regions), the locator() returns the coordinates of the selected points. They have a reasonable value. However, when I plot them, the results are not that accurate (i.e. none of the chosen point lie in the selected region). Can you explain to me what's the problem?
library(sf)
nc = st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE)
plot(nc["SID74"], reset = FALSE)
pts <- locator()
pts <- st_sfc(st_multipoint(do.call(cbind, pts)), crs = st_crs(nc))
plot(pts, add = TRUE, pch = 16)
This is an interesting problem; I don't have an answer but I suspect that the issue will be environment related.
I ran your code on Linux (with a small adjustment for target number of points / clicks) and the code behaves as expected. I was able to place three points inside the Mecklenburg (as in Charlotte of Mecklenburg-Strelitz) county.
As locator() seems to use X11 (which is in my case native, but on Windows wrapped in a kind of convoluted fashion) I speculate that your problem may be environment related.
library(sf)
nc = st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE)
plot(nc["SID74"], reset = FALSE)
pts <- locator(n = 3) # to speed up the process
pts <- st_sfc(st_multipoint(do.call(cbind, pts)), crs = st_crs(nc))
plot(pts, add = TRUE, pch = 16)
I'm trying to create a choropleth map in R. I've merged my shapefiles and data files. I'm trying to create a palette for the different colours I want my data to display in on my choropleth. When I use the colorNumeric function it returns an error message.
library(leaflet)
library(rgdal)
library(tigris)
library(dplyr)
LAsMap <- readOGR(dsn = "C:/Users/LocalAuthorityShapefiles",
layer = "Local_Authority_Districts_December_2017_Generalised_Clipped_Boundaries_in_United_Kingdom_WGS84")
data <- read.csv(file = "C:/projects/N123.csv")
data_merged_map <- geo_join(LAsMap, data, "lad17cd", "lad17nm")
mypalette <- colorNumeric( palette="viridis", domain=data_merged_map$N456)
I expect the output to just run the code and create a palette in my workspace but instead the "Wasn't able to determine range of domain" error message appears.
For me, this happened because I had -Inf values. Originally they were 0s, but I log10() transformed the vector, and that's what caused them to be -Inf for me.
Problem:
The add_grid function in the R mapdeck package is very exciting. However, following the CRAN documentation, I cannot seem to get any data to actually plot on the returned map.
In other words, the map returns, but no data is plotted. Is this a known bug?
Code:
library(tidyverse)
library(mapdeck)
# - Enter mapdeck key ... Note that it is user-specific
key <- rstudioapi::askForPassword()
# - Read Example Data Set
df <- read.csv(paste0(
'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/',
'examples/3d-heatmap/heatmap-data.csv'
))
# - Plot Data ... Note how the map returns, but not the data
mapdeck( token = key, style = 'mapbox://styles/mapbox/dark-v9', pitch = 45 ) %>%
add_grid(
data = df
, lat = "lat"
, lon = "lng"
, cell_size = 5000
, elevation_scale = 50
, layer_id = "grid_layer"
)
Created on 2018-09-23 by the reprex package (v0.2.1)
Output:
This is not necessarily a 'bug' inside mapdeck itself, but more the way mapdeck communicates with RStudio. There are conflicts between the different javascript versions they use.
If you open the plot in a browser (by pressing the show in new window button in Rstudio) you should get your plot.
I've got this issue logged, but don't know the way forward yet.
Is it possible to style a TopoJSON file from its features for a choropleth using R/leaflet? Tried a few things, and I'm not sure if this is impossible with the leaflet package or if I just don't have the syntax right, especially accessing the properties to enter in the pal() function. Here's what I have:
pal<-colorNumeric(palette ="YlOrRd",domain = USAdata$GINI) #USAdata data frame I merged with the spdf before converting it to shp/topojson
map<-leaflet() %>%
addTiles(options=tileOptions(minZoom = 3)) %>%
setMaxBounds(-167.276413,5.499550,-52.233040, 83.162102) %>%
setView(93.85,37.45,zoom =3) %>%
#addGeoJSON(geojson = jso5)
addTopoJSON(topojson=jso, fillColor = ~pal("GINI"))
#addPolygons(data=poly)
this throws up an error:
"Error in UseMethod("doResolveFormula") :
no applicable method for 'doResolveFormula' applied to an object of class "NULL""
I also tried converting it to an R object the topojson with fromJSON() and adding style elements, but this won't load after I try send it back with toJSON().
Not sure if relevant, but the topojson was created from a shapefile made following the instructions here:
with cl:
topojson -o 'USApuma.json' --shapefile-encoding utf8 --id-property=+GEOID10 -p GINI,+STATEFP10,+GEOID10 -- 'usaetest.shp'
then read in with readLines().
Eventually trying to throw this into a shiny app. Here's some examples I've been following.
Do you need to use TopoJSON? If not consider using the tigris package (disclosure: I created and maintain the package). It'll get you access to just about any Census geographic dataset you need, and plays nicely with leaflet. Here's a brief example in line with what you are doing. For example, you can get all PUMAs in the continental US with the following code:
library(readr)
library(tigris)
library(leaflet)
us_states <- unique(fips_codes$state)[1:51]
continental_states <- us_states[!us_states %in% c("AK", "HI")]
pumas_list <- lapply(continental_states, function(x) {
pumas(state = x, cb = TRUE)
})
us_pumas <- rbind_tigris(pumas_list)
I've generated a sample dataset that measures PUMA median household income for this example; the geo_join function from the tigris package can merge the dataset to the spatial data frame us_pumas:
puma_income <- read_csv('http://personal.tcu.edu/kylewalker/data/puma_income.csv')
joined_pumas <- geo_join(us_pumas, puma_income, 'GEOID10', 'GEOID')
We can then plot with Leaflet:
pal <- colorQuantile(palette = 'YlOrRd', domain = joined_pumas$hhincome, n = 7)
leaflet(joined_pumas) %>%
addProviderTiles('CartoDB.Positron') %>%
addPolygons(weight = 0.5, fillColor = ~pal(hhincome),
color = 'lightgrey', fillOpacity = 0.75,
smoothFactor = 0.2) %>%
addLegend(pal = pal,
values = joined_pumas$hhincome)
If you are planning to build a Shiny app, I'd recommend saving out the PUMAs you obtain from tigris first as a .rda file and reading it in with your Shiny script so you don't have to rbind_tigris every time.
I am trying to plot coordinate points on a map, but I get the plot.new error. Could you please help?
library(maptools)
library(ggmap)
library(mapproj)
table <- read.table("table.txt", header=TRUE, sep=",")
map <- get_map(location = 'France', zoom = 6, maptype = c("toner"))
points(table$LONG, table$LAT, pch=21, bg=color, cex=0.7, lwd=.4)
ggmap(map)
Here is an idea of what the table looks like:
CITY,LAT,LONG
Paris,48.856667,2.351944
Lyon,45.766944,4.834167
Bordeaux,44.838611,0.578334
Try geom_point:
library(maptools)
library(ggmap)
library(mapproj)
city <- c("Paris", "Lyon", "Bordeaux")
my.lat <- c(48.856667, 45.766944, 44.838611)
my.long <- c(2.351944, 4.834167, 0.578334)
points <- data.frame(lon=my.long, lat=my.lat)
map <- get_map(location = c(left = -5, bottom = 42, right=9, top = 51 ), source = 'stamen', maptype = 'toner')
france <- ggmap(map, extent = 'normal')
france + geom_point(data=points, col="red")
Try the command ?ggmap for a list of great examples. I think the manual has done a good job, because before I read your question, I didn't even know of any of these functions. Thanks! I've learned something new.
Learn to walk before you try and run.
The points function adds points to an existing graphic. You haven't got an existing graphic yet (unless you've already done something you've not showed us).
Hence if you do points before starting a plot, you'll get an error. eg:
points(1:10,1:10) # plot.new error
plot(1:10,1:10) # no error, starts a new plot
points(10:1,1:10) # adds extra points, no error.
All your stuff with ggplot is irrelevant. Also, this is not about statistics, so you should have posted to StackOverflow. I've flagged this and it might get migrated...