riatelab/cartography

histogram legend

chrijo opened this issue · 5 comments

Hi everybody,

first of all, I like your package very much and I'm using it for cartography purpose for while. However, I saw a nice feature in the tmap package, I hope to realize with cartography. In tmap one is able to plot a histogram (tm_fill(..., legend.hist = TRUE)) to the corresponding legend for a choropleth map (e.g. https://workshop.mhermans.net/thematic-maps-r/04_plot.html). Is it possible to do this with cartography?

Hi,
Yes, that would be a nice feature.
I already tried something like that here.
I'm not sure that's the way it should be done in cartography.

Following the WIP of @rCarto , I have been working on further develop a feature like that: https://github.com/dieghernan/cartography/blob/histv2/R/maphist.R

There is still a point on thinking if this needs to be integrated into a legend or if it can live as standalone feature. In case of integration, the problem on legendChoro is that it doesn't handle real data inputs, just labels, so a call to histogram there would need major changes.

A example on how the WIP compares with tmap so far:

library(sf)
library(tmap)
mtq <- st_read(system.file("gpkg/mtq.gpkg", package="cartography"))
mtq$chomage=mtq$CHOM/mtq$ACT
cols=carto.pal("wine.pal",4)

# TMAP OPTION--------
tm_shape(mtq) +
  tm_borders(col = 'white', lwd = 0.3) +
  tm_fill(col = 'chomage', title = 'Chomage', legend.hist = TRUE,
          palette = cols) +
  tm_legend(legend.outside = TRUE)

image

# CARTOGRAPHY OPTION--------
par(mar=c(0,0,0,3))
brks=as.double(pretty(mtq$chomage))
choroLayer(mtq,var="chomage", breaks = brks, col=cols,
           legend.pos="topright", legend.title.txt="Chomage",
           legend.values.rnd=2)

maphist(mtq$chomage,breaks = brks,pos="right", col=cols)

image

An attempt to integrate it:

library(cartography)
library(sf)
mtq <- st_read(system.file("gpkg/mtq.gpkg", package="cartography"))
# Population density
mtq$POPDENS <- 1e6 * mtq$POP / st_area(x = mtq)
par(mar = c(0.5,0.5,2,0.5))
bks <- getBreaks(mtq$POPDENS, method = "quantile", nclass = 6)
cols <- carto.pal(pal1 = "wine.pal", 6)
choroLayer(x = mtq, var = "POPDENS", breaks = bks, col = cols,
           border = NA, legend.title.txt = "Population\nDensity",
           legend.hist = TRUE) #NEW PARAMETER
layoutLayer("Testing histogram", theme = "wine.pal")

image

Hello @dieghernan,

thanks, both solutions look great. However, I agree with you in that the standalone Version seems more felxible. Great job!