This is the second « big » feature coming with branch 0.2 of
rleafmap (now on CRAN!). With this new version you can write popups content in R Markdown which will be processed when you generate the map. This can be useful to format popups using markdown syntax (if you need more control remind that popups can also be formatted with html tags). More interesting with R Markdown is the possibility to include outputs of R code chunks. Thus, results, simulations and plots can be easily embedded within popups content.
To activate R Markdown for a layer you just have to pass the R Markdown code to the
popup argument and set
The chunkerize function
You can write your R code chunks manually but you can also use the function
chunkerize which tries to make your life simpler. This function has two purposes:
- It turns a function and its arguments into an R code chunk.
- It can decompose the elements of a list and use them as values for a given argument.
The latter may be useful when you have different features on your map and you want to execute the same function for each of them but with different data as input. This can be done by tagging the list containing the data with a star character (*). See the following example:
Data you need for the example: download and unzip
First we load the packages we need:
Then we load the data: a shapefile of regions and a dataframe giving the evolution of the population for each region.
reg <- readShapePoly("regions-20140306-100m") reg <- reg[c(-11,-12,-16,-19,-20),] pop <- read.csv("population.txt", sep = "\t", row.names = 1) pop <- pop[rev(rownames(pop)), sort(names(pop))]
We prepare some colors for the map and a legend:
gcol <- rev(heat.colors(5)) gcut <- cut(as.numeric(pop["2012", ]), breaks = c(0, 2000000, 3000000, 4000000, 8000000, 12000000)) reg.col <- gcol[as.numeric(gcut)] reg.leg <- layerLegend(style = "polygons", title = "Population", labels = levels(gcut), fill.col = gcol)
We prepare the data for
chunkerize: pop is already a list, since it is a dataframe but for clarity we turn it into a simple list.
Year <- as.numeric(rownames(pop)) L <- as.list(pop) L2 <- as.list(names(L))
Now is the trick. We create a chunk based on a plot function. We provide 5 arguments (names and values). Each arg.values is going to be recycled, except
L2 which are tagged with a star. In that case, each element of these lists is going to be used as values.
popup <- chunkerize(FUN = plot, arg.names = c("x", "y", "type", "ylab", "main"), arg.values = c("Year", "*L", "'b'", "'Population'", "*L2"))
Now we just have to create the layers and compile the map:
cdbpos.bm <- basemap("cartodb.positron.nolab") reg.map <- spLayer(reg, fill.col = reg.col, legend = reg.leg, popup = popup, popup.rmd = TRUE) writeMap(cdbpos.bm, reg.map)
Et voilà ! There is a problem with Rstudio and Firefox. It happens that popups do not appear where they should on the first click. It works fine on Chromium.