riatelab / cartography Goto Github PK
View Code? Open in Web Editor NEWThematic Cartography for R
Home Page: http://riatelab.github.io/cartography/docs/
Thematic Cartography for R
Home Page: http://riatelab.github.io/cartography/docs/
Hi,
we are using the cartography package to look at different variables of interest across Europe. We take the data for our variables from EUROSTAT via the eurostat package where they use the latest NUTS2 version which is from 2013. As the NUTS 2 data in your package is from 2006 we face the following problem: some NUTS2 regions in Italy, Finland and Germany cannot be displayed because they got renamed (Map): emprt_16_map.pdf
Our script to plot the map looks like this:
BIP <- get_eurostat("nama_10r_2gdp", time_format = "raw")
data(nuts2006)
opar <- par(mar = c(0,0,0,0))nuts_2 <- nuts2.df$id
mapdata <- filter(BIP, unit == "PPS_HAB", time == max(time), geo %in% c(nuts_2))
mapdata <- select(mapdata, geo, values)
names(mapdata)[1] <- "id"Merge nuts and bip
nuts2.df <- merge(nuts2.df, mapdata, by="id")
cols <- c("#d7191c","#fdae61","#ededad","#a6d96a","#1a9641")
Plot a layer with the extent of the EU28 countries with only a background color
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
Plot non european space
plot(world.spdf, col = "#F9F9F7", border=NA, add=TRUE)
Plot the bip
choroLayer(spdf = nuts2.spdf, # SpatialPolygonsDataFrame of the regions
df = nuts2.df, # data frame with bip
var = "values", # bip field in df
nclass = 5,
method = "quantile",
col = cols, # colors
border = "grey40", # color of the polygons borders
lwd = 0.5, # width of the borders
legend.pos = "topright", # position of the legend
legend.title.txt = "BIP je\nEinwohner", # title of the legend
legend.values.rnd = 0, # number of decimal in the legend values
add = TRUE) # add the layer to the current plotPlot a layer of countries borders
plot(nuts0.spdf,border = "grey20", lwd=0.75, add=TRUE)
plot(nuts2.spdf,border= "grey20", lwd=0.2, add=TRUE)par(opar)
Do you have any suggestions how we could solve this problem? Did we miss an important setting?
We can solve the problem by renaming the "geo" variable but if there is a better way we would be glad.
Thanks for your help!
Find a way to spot the NAs automatically
I could not find the option of adjust the transparency level on all colors! Is it possible to add the option transparency when you plot with colors (I did not find).
regards
Byman
In the vignette of the current CRAN version, for exemple the choropleth map, the south arrow is not displayed, although it should with the use of south = TRUE
(see code below)
layoutLayer(title = "Demographic Trends", author = "cartography",
sources = "Eurostat, 2008", frame = TRUE, col = NA,
scale = NULL,coltitle = "black",
south = TRUE) # add a south arrow
Good morning,
When I use the PropSymbolsLayer function with the spdf and df parameters (instead of x parameter), I obtain the following error code :
Error: In ‘udunits_from_proj[x$units]’, ‘udunits_from_proj’ and ‘x’ are not recognized by udunits.
See a table of valid unit symbols and names with valid_udunits().
Add custom user-defined units with install_symbolic_unit().
By the way, the corresponding code in the R documentation Platform does not work in my laptop :
data("nuts2006")
plot(nuts0.spdf, col = "grey60",border = "grey20")
propSymbolsLayer(spdf = nuts0.spdf, df = nuts0.df,
var = "gdppps2008",
symbols = "bar", col = "#B00EF0",
legend.pos = "right",
legend.title.txt = "GDP\nin Millions PPS (2008)",
legend.style = "e")
I got the same error message.
Is someone can help me?
Thanks a lot.
Kevin
Is it possible to represent three variables as three bars for each nuts region in Europe? the example is only with one variable but I would like to have three at the same time with three different bars.
Thanks,
I don't know how it can be done, but it can be : https://twitter.com/slowkow/status/696710285080600578
This would help with the always-happening issue of plot window size not being adapted.
title color, arrow, font(?)...
Thanks for this awesome package.
I am wondering if there is a way to get identical symbol classes (and legend) using propSymbolsLayer
with the aim of comparing two maps. Using fixmax
does not help (see the maps below; breaks and number of symbols change depending on the range of the input variable).
Ideally, it would also be nice if it was possible to set the symbol breaks as it is the case for ChoroLayer.
I think it should be easy to implement in the propSymbolsLayer
function (need a bit of time to look at it).
#################
# First map
#################
library(sf)
mtq <- st_read(system.file("shape/martinique.shp", package="cartography"))
# Countries plot
plot(st_geometry(mtq), col = "lightblue4",border = "lightblue3", bg = "lightblue1")
# Population plot on proportional symbols
propSymbolsLayer(x = mtq, var = "P13_POP",
symbols = "circle", col = "white",
fixmax = 85000,
legend.pos = "right", border = "grey",
legend.title.txt = "Total\npopulation (2013)",
legend.style = "c")
# Layout plot
layoutLayer(title = "Population in Martinique",
sources = "INSEE, 2016", theme = "blue.pal",
scale = NULL, frame = FALSE)
#################
# Second map
#################
mtq$P13_POP <- mtq$P13_POP - 5000
# Countries plot
plot(st_geometry(mtq), col = "lightblue4",border = "lightblue3", bg = "lightblue1")
# Population plot on proportional symbols
propSymbolsLayer(x = mtq, var = "P13_POP",
symbols = "circle", col = "white",
fixmax = 85000,
legend.pos = "right", border = "grey",
legend.title.txt = "Total\npopulation (2013)",
legend.style = "c")
# Layout plot
layoutLayer(title = "Population in Martinique",
sources = "INSEE, 2016", theme = "blue.pal",
scale = NULL, frame = FALSE)
Bonsoir,
Sous Windows 10, R version 3.3.2patched, dans l'environnement Rgui, j'ai une erreur
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘spChFIDs’ for signature ‘"SpatialPolygonsDataFrame", "integer"’
En environnement "Rscript.exe", je n'ai pas d'erreur.
La partie significative de mon script
library(sp)
library(rgdal)
library(rgeos)
library(cartography)
varDir <- sprintf("%s/bvi35/CouchesVilaineAval", Drive);
dsn <- sprintf("%s/Nord.shp", varDir)
layer <- ogrListLayers(dsn)
spdf <- readOGR(dsn, layer=layer, stringsAsFactors=FALSE)
spdf <- spTransform(spdf, CRS("+init=epsg:2154"))
grille <- getGridLayer(spdf=spdf,cellsize = 1000)
J'avais ce même comportement en R version 3.3.1.
Dans le mode Rgui, la commande "names()" fonctionne de manière différente, c'est peut-être une piste ?
Et merci pour votre package qui est super pratique !
sp - sf compatible?
Hi,
first thanks a lot for the great package!
I've just got a problem when using choroLayer with nclass=6 and method="sd".
Wouldn't get the number of classes I've asked for. Any idea why?
Thanks a lot!
Congrats for your work.
It is possible to add size for title and source in LayoutLayer ?
Thank you in advance.
The getGridLayer example now fails with PROJ 6.1.0 on st_crs(x) == st_crs(y) with current sf (@edzer) and:
> mygrid <- getGridLayer(x = mtq, cellsize = 3e7, type = "hexagonal", var = "POP")
Error in st_geos_binop("intersects", x, y, sparse = sparse, prepared = prepared) :
st_crs(x) == st_crs(y) is not TRUE
> sf_extSoftVersion()
GEOS GDAL proj.4 GDAL_with_GEOS
"3.7.2" "3.0.0" "6.1.0" "true"
> debug(getGridLayer)
...
Browse[2]> st_crs(x)
Coordinate Reference System:
EPSG: 32620
proj4string: "+proj=utm +zone=20 +datum=WGS84 +units=m +no_defs"
...
Browse[2]> st_crs(grid)
Coordinate Reference System:
EPSG: 32620
proj4string: "+proj=utm +zone=20 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
Browse[2]>
Error in st_geos_binop("intersects", x, y, sparse = sparse, prepared = prepared) :
st_crs(x) == st_crs(y) is not TRUE
>
Hello,
Would it be possible to add a legend.nodata.col parameter to the typoLayer() function to be able to have another color than white?
Thank you.
Pierre-Yves
horiz=TRUE
=> bottomleft horizontal, horiz = FALSE
bottom right vertical for source and author displayHi , I was trying to use your awesome package to pie charts with county map. IS there a way instead draw bubbles to draw the pie chart?
Hello, it would be nice to have symbols like triangleTop and triangleBottom (or circles) in propSymbolsChoroLayer().
In this way, printing two layers, one could use also the colour of the triangles - and not just the size, as in propTrianglesLayer() - as the measure of a further dimension.
It would also make propTrianglesLayer() redundant.
A more general approach would be to print circles with two further parameters: the initial angle and the arc angle: in this way one could, using repeated calls to this method, compose a "cake" in each polygon where the size and/or the colour of each slice would come from a different variable.
Cheers !
Using a simple workaround, I have added color gradient support to gradLinkLayer
function. You may want to consider adding this feature to the package.
Here are the changes I have made:
In gradLinkLayer
:
plot(sf::st_geometry(link),
col = if(length(col) > 1){col[as.factor(lwdMap)]}else{col},
lwd = lwdMap, add = add)
In legendGradLines
:
segments(xref, yref + height/2 + i * height + i * delta2 +
(height + delta2)/2, xref + width, yref + i * height +
i * delta2 + height/2 + (height + delta2)/2, lwd = lwd[j],
col = ifelse(length(col > 1), col[j], col),
lend = 1)
library(sp)
data("nuts2006")
# Create a link layer
twincities.sf <- getLinkLayer(x = nuts2.spdf, df = twincities.df[,1:2])
figdim <- getFigDim(x = districtsShp, width = 800, mar = c(0,0,1.2,0), res = 100)
cols <- c('#edf8fb','#b3cde3','#8c96c6','#8856a7','#810f7c')
# set figure margins
par(mar = c(0,0,1.2,0))
# Plot the links - Twin cities agreements between regions
plot(nuts0.spdf, col = "grey60",border = "grey20")
gradLinkLayer(x = twincities.sf, df = twincities.df,
legend.pos = "topright",
var = "fij", breaks = c(2,5,15,20,30), lwd = c(0.1,1,4,10),
col = "#92000090", add = TRUE)
figdim <- getFigDim(x = districtsShp, width = 800, mar = c(0,0,1.2,0), res = 100)
cols <- c('#edf8fb','#b3cde3','#8c96c6','#8856a7','#810f7c')
# set figure margins
par(mar = c(0,0,1.2,0))
# Plot the links - Twin cities agreements between regions
plot(nuts0.spdf, col = "grey60",border = "grey20")
gradLinkLayer_modif(x = twincities.sf, df = twincities.df,
legend.pos = "topright",
var = "fij", breaks = c(2,5,15,20,30), lwd = c(0.1,1,4,10),
col = c('#ffffb2','#fecc5c','#fd8d3c','#e31a1c'), add = TRUE)
Bonjour,
Tout d'abord merci pour votre travail.
J'ai un problème lorsque j'utilise des cartes avec la fonction propSymbolsLayer, la légende n'apparaît pas parfaitement : il y a décalage entre les cercles et les valeurs qui apparaissent à côté.
Savez-vous ce qui peut poser ce genre de problèmes ?
En vous remerciant par avance,
Cordialement,
the spdf needs to be projected
Error in RGEOSBinTopoFunc(spgeom1, spgeom2, byid, id, drop_lower_td, unaryUnion_if_byid_false, :
TopologyException: Input geom 0 is invalid: Self-intersection at or near point (..........)
In addition: Warning message:
In rgeos::gBuffer(spdf, byid = TRUE, width = distance, quadsegs = 1, :
Spatial object is not projected; GEOS expects planar coordinates
disckLayer does not manage NA values well
In all relevant functions
D'abord félicitations pour cette nouvelle version du package.
La légende n'est pas très lisible et comporte des erreurs entre la taille du triangle et la valeur.
Voici le code de test
library(sp)
library(sf)
library(raster)
library(cartography)
xmin <- 30000
xmax <- 33000
ymin <- 30000
ymax <- 33000
sp <- as(extent(xmin, xmax, ymin, ymax), "SpatialPolygons")
# en Lambert 93
proj4string(sp) <- CRS("+init=epsg:2154")
spdf <- SpatialPolygonsDataFrame(sp, data.frame(ID=1:length(sp)))
# Création d'une grille régulière
x <- sf::st_as_sf(spdf)
grille.sf <- st_make_grid(x , 1000)
# nombre de mailles
nb <- length(grille.sp)
# conversion en spdf
grille.sp <- as(grille.sf, "Spatial")
grille.spdf <- SpatialPolygonsDataFrame(grille.sp, data.frame(ID=1:nb, a=sample(1:100, nb, replace=T), b=sample(1:100, nb, replace=T), row.names=row.names(grille.sp)))
print(grille.spdf@data)
propTrianglesLayer(spdf=grille.spdf, var1="a", var2="b", add=FALSE)
Warning when using points layer with add=F
=> use plot(..., type = "n") instead of plot(..., border=NA, col = NA)
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?
Je viens d'utiliser cette fonction pour générer une grille au pas de 1000 mètres.
Les coordonnées du centre des mailles sont en multiple de 1000, ce qui fait que les côtés sont décalés de 500 mètres.
Je voudrais obtenier un maillage standard Lambert93 avec les côtés en multple de 1000.
J'ai recopié la fonction getGridLayer, pour faire cette modification
boxCoordX <- seq(from = boundingBox[1,1]-500, to = boundingBox[1,2]+500, by = cellsize)
boxCoordY <- seq(from = boundingBox[2,1]-500, to = boundingBox[2,2]+500, by = cellsize)
mais j'ai une erreur avant ces instructions
Error in names(spdf@data) : argument inutilisé spdf@data)
Je suis en Windows10/R 3.2.2/cartography 1.1
Et sinon un grand merci pour ce package qui facilite beaucoup de traitements
Error in UseMethod("st_centroid") :
pas de méthode pour 'st_centroid' applicable pour un objet de classe "c('SpatialPointsDataFrame', 'SpatialPoints', 'Spatial', 'SpatialPointsNULL', 'SpatialVector')"
propTrianglesLayer
propSymbolsTypoLayer
typoLayer
dotDensityLayer
Bonjour,
Je veux produire une grille "Lambert" avec des mailles entières.
En modifiant getGridSquare, j'arrive bien à ce que les mailles soient alignées sur le quadrillage Lambert.
boundingBox[,1] <- boundingBox[,1] - rounder[,1] - cellsize/2 boundingBox[,2] <- boundingBox[,2] - rounder[,2] + cellsize + cellsize/2
Par contre je ne trouve pas comment enlever l'intersection des mailles.
Je voudrais mettre un nom de maille du type E9999N9999, la partie numérique dépendant du coin en bas à gauche. Cela est-il possible ?
Hello again!
Quick question! Is it possible to use custom color gradients?
For example, is it possible to set the lowest value as "white" and highest value as "dodgerblue4"?
I saw the post about using hex colors but did not have luck...
values of the second color ar not ok. Abs problem?
Consider using rosm package instead of OpenStreetMap package for raster tile plotting. (because of rjava intallation, and time needed to download the tiles )
make scale and arrow customizable and positionable.
If var
is in spdf
and df
is missing add a default behavior to set df
to spdf@data
.
Apply to all relevant functions. (suggestion Rémy Drouilhet)
Thank you so much for your wonderful package! I am really enjoying the package so far.
I had one quick question regarding legends. If you see my screenshot, I have set 6 manual breaks, but they are not reflected in the legend. Is there something missing in my code?
#add choropleth layer
choroLayer(
x = usa,
var = "one",
method = "geom",
breaks = c(0, 0.2, 0.4, 0.6, 0.8, 1),
nclass= 7,
col = carto.pal(pal1 = "blue.pal", n1 = 7),
border = "white",
lwd = 0.001,
legend.pos = "bottomright",
legend.title.txt = "Test name",
add = TRUE
)
)
Hello, looking into the script generating the vignette map, i've found that it's possible to use the gridding functions to generate a regular-grid point map, Bertin-style.
Cf. my presentation here : http://www.uoh.fr/front/document/ee86e66d/cdbb/47df/ee86e66d-cdbb-47df-a13e-bf502c963b0a/UOHGEOprod/Module116/pages/s6/page2417.xml
I'm not a pro of R, but here is my little script, using the data from the package:
library(cartography)
data(nuts2006)
# Plot basemaps
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
plot(world.spdf, col = "#E3DEBF80", border=NA, add=TRUE)
plot(nuts0.spdf, border = "white", col = "#E3DEBF", lwd= 1.1, add=T)
# Compute the grid and its base values
mygrid <- getGridLayer(spdf = nuts0.spdf,cellsize = 50000)
datagrid.df <- getGridData(mygrid, nuts0.df, "pop2008", dfid=NULL)
# Compute the number of points in the polygons
np<-as.data.frame(table(mygrid$df$id_geo)
# Compute the value for each point of the grid
# Load dplyr to cross join the tables
library(dplyr)
# Compute the join between the grid and the list of point numbers by polygons
a <- inner_join(np, mygrid$df, by = c("Var1" = "id_geo"))
# Compute the join with the datagrid
c <- inner_join(a, datagrid.df)
# Compute the join with the data source
d<-inner_join(nuts0.df, c, by = c("id" = "Var1"))
# Calculate the value for each point of the grid (var / nb pts).
d$pop2008grid = d$pop2008.x / d$Freq
# Draw the map
propSymbolsLayer(spdf = mygrid$spdf, df = d, spdfid = "id", dfid = "id_cell", legend.pos = "n", border = "white", var = "pop2008grid", k=0.0001, col="darkblue", add=TRUE)
Thanks for your work, it'll be very useful for my students :)
Hi,
You have a color pallet for qualitative variables, but there seems there is no way to display the correct categorical variable names in the legend? I.e., I can recode to quantitative for the mapping, but no way to reflect real text values in legend. Is this a limitation or am I missing a parameter somewhere?
Les boites et les labels sont décalés quand breakval=TRUE
Bonjour,
Déjà un grand merci pour votre travail, votre package est vraiment très utile et facile d'accès.
J'aurais une question concernant la fonction labelLayer. Est-il possible lors de l'affichage de faire apparaître un halo ou une couleur de fond derrière les caractères affichés ? Si ce n'est pas le cas, est-ce que cela est envisagé dans une version future de la fonction ?
En vous remerciant par avance pour votre réponse,
Cordialement,
Baptiste MARTIN
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.