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.
Related
I am working with the R programming language. Using the following code, I made an interactive map with the "leaflet" library :
Lat = round(runif(5000,43,44), 4)
Long = round(runif(5000,79,80), 4)
a <- rnorm(5000,100,10)
map_data <- data.frame(Lat, Long, a)
map_data$Long = -1 * map_data$Long
#load libraries
library(leaflet)
library(leaflet.extras)
#make heatmap for variable "a"
leaflet(map_data) %>%
addTiles(group="OSM") %>%
addHeatmap(group="a", lng=~Long, lat=~Lat, max=.6, blur = 60)
Does anyone know if it is possible to understand the exact (math) formulas behind the coloring/shading in this map? I tried consulting the official documentation for the functions used to create this map (https://cran.r-project.org/web/packages/leaflet.extras/leaflet.extras.pdf) , but no where does it explain how the colors are finalized. I suspect that this somehow might be related to "kernel density estimation". Furthermore, I have a feeling that the "max" and the "blur" options are actually parameters used in the final coloring of this map.
Does anyone know if it is possible to understand the exact formula used behind the coloring?
Thanks
Is there a way to make popup graphs appear on hover (rather than click) in Mapview? Alternatively, is it possible for the graphs to appear open by default? Rather than produce my own reproducible example, I would defer to the example given with the R Mapview documentation.
I am fairly new to R and Mapview so any guidance is greatly appreciated!
I've just pushed an update to package leafpop which provides the popup functionality used in mapview. This should provide what you want (at least partly - as mapview() will still need to be updated). This allows you to now specify tooltip = TRUE in addPopupImages (in addPopupGraphs via ...). Note that it is encouraged to use addPopup* functions over the classic popup* functions because they also work in non-interactive setting, e.g. when saving a map locally.
library(sf)
library(leaflet)
library(lattice)
library(leafpop)
pt = data.frame(x = 174.764474, y = -36.877245)
pt = st_as_sf(pt, coords = c("x", "y"), crs = 4326)
p2 = levelplot(t(volcano), col.regions = terrain.colors(100))
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pt, group = "pt") %>%
addPopupGraphs(
list(p2)
, group = "pt"
, width = 300
, height = 400
, tooltip = TRUE
)
Not sure when and how to integrate this into mapview() as this is a bit more complicated than the classic popup* functions (because we need to know something about the map object we create with mapview before we create it...). In any case, I hope this is at least partly useful and helps resolve your issue.
My data is like this:
ZIPcode Cases longi lati
43613 1 -83.604452 41.704307
44140 1 -81.92148 41.48982
46052 1 -86.470531 40.051603
48009 22 -83.213883 42.544619
48017 6 -83.151815 42.535396
48021 7 -82.946167 42.463894
48025 19 -83.265758 42.523195
I want to get a map similar to this (if you can see it) in R. The outline should be zipcodes and the shading should be according to number of cases, darker as cases increase.
I'm very new to R. Tried a lot of code I found online but can't get what I want. Any help is appreciated. Can this be done in base SAS ?
Thank you!
enter image description here
Definetly you can do it in R, I put together a reprex (reproducible example) for you. Key points:
You need to load into R a .shp file (or .geojson, .gpkg, etc.). That is an actual file with the outline of your map. For ZIPCODES I found a R package, tigris, that does that for you, if not you'll need to load it by yourself.
For handling mapping objects (load, transform, .etc), sf package is your best friend.
For plotting, in this example I used cartography, but you can use several different package, as ggplot2 or tmap.
Last line is that, given your data (and if I didn't get the ZIPCODEs wrong), a map as the one you shown (choropleth map) maybe is not the best options. Have a look here to see other alternatives.
library(sf) #Overall handling of sf objects
library(cartography) #Plotting maps package
#1. Create your data
yourdata <- data.frame(ZCTA5CE10=c("43613", "44140", "46052",
"48009","48017", "48021","48025"),
Cases=c(1,1,1,22,6,7,19)
)
#2. Download a shapefile (shp,gpkg,geojson...)
library(tigris) #For downloading the zipcode map
options(tigris_use_cache = TRUE)
geo <- st_as_sf(zctas(cb = TRUE, starts_with = yourdata$ZCTA5CE10))
#Overall shape of USA states
states <- st_as_sf(states(cb=TRUE))
#For plotting, all the maps should have the same crs
states=st_transform(states,st_crs(geo))
#3. Now Merge your data
yourdata.sf=merge(geo,yourdata)
#4. Plotting
par(mar=c(1,1,1,1))
ghostLayer(yourdata.sf)
plot(st_geometry(states), add=TRUE)
choroLayer(yourdata.sf,
var="Cases",
add=TRUE,
border = NA,
legend.pos = "right",
legend.frame = TRUE)
layoutLayer(title = "Cases by ZIPCODE",
theme = "blue.pal",
scale = FALSE,
sources = "Source; your question on SO",
author = "by dieghernan, 2020"
)
Created on 2020-02-27 by the reprex package (v0.3.0)
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)
I'm trying to trouble shoot why Drake plots are not showing up with readd() - the rest of the pipeline seem's to have worked though.
Not sure if this is caused by minfi::densityPlot or some other reason; my thoughts are the later as it's also not working for the barplot function which is base R.
In the RMarkdown report I have readd(dplot1) etc. in the chunks but the output is NULL
This is the code I have in my R/setup.R file:
library(drake)
library(tidyverse)
library(magrittr)
library(minfi)
library(DNAmArray)
library(methylumi)
library(RColorBrewer)
library(minfiData)
pkgconfig::set_config("drake::strings_in_dots" = "literals") # New file API
# Your custom code is a bunch of functions.
make_beta <- function(rgSet){
rgSet_betas = minfi::getBeta(rgSet)
}
make_filter <- function(rgSet){
rgSet_filtered = DNAmArray::probeFiltering(rgSet)
}
This is my R/plan.R file:
# The workflow plan data frame outlines what you are going to do
plan <- drake_plan(
baseDir = system.file("extdata", package = "minfiData"),
targets = read.metharray.sheet(baseDir),
rgSet = read.metharray.exp(targets = targets),
mSetSq = preprocessQuantile(rgSet),
detP = detectionP(rgSet),
dplot1 = densityPlot(rgSet, sampGroups=targets$Sample_Group,main="Raw", legend=FALSE),
dplot2 = densityPlot (getBeta (mSetSq), sampGroups=targets$Sample_Group, main="Normalized", legend=FALSE),
pal = RColorBrewer::brewer.pal (8,"Dark2"),
dplot3 = barplot (colMeans (detP[,1:6]), col=pal[ factor (targets$Sample_Group[1:6])], las=2, cex.names=0.8, ylab="Mean detection p-values"),
report = rmarkdown::render(
knitr_in("report.Rmd"),
output_file = file_out("report.html"),
quiet = TRUE
)
)
After using make(plan) it looks like everything ran smoothly:
config <- drake_config(plan)
vis_drake_graph(config)
I am able to use loadd() to load the objects needed for one of these plots and then make the plots, like this:
loadd(rgSet)
loadd(targets)
densityPlot(rgSet, sampGroups=targets$Sample_Group,main="Raw", legend=FALSE)
But the readd() command doesn't work?
The output in the .html for dplot3 looks weird...
Fortunately, this is expected behavior. drake targets are return values of commands, and so the value of dplot3 is supposed to be the return value of barplot(). The return value of barplot() is actually not a plot. The "Value" section of the help file (?barplot) explains the return value.
A numeric vector (or matrix, when beside = TRUE), say mp, giving the coordinates of all the bar midpoints drawn, useful for adding to the graph.
If beside is true, use colMeans(mp) for the midpoints of each group of bars, see example.
So what is going on? As with most base graphics functions, the plot from barplot() is actually a side effect. barplot() sends the plot to a graphics device and then returns something else to the user.
Have you considered ggplot2? The return value of ggplot() is actually a plot object, which is more intuitive. If you want to stick with base graphics, maybe you could save the plot to an output file.
plan <- drake_plan(
...,
dplot3 = {
pdf(file_out("dplot3.pdf"))
barplot(...)
dev.off()
}
)