trouble using RColorBrewer with spplot - r

I feel like many similar questions have been asked but I haven't found a solution to my problem yet in the related questions.
I am trying to change the colors on my map using spplot and the col.region command.
I have tried setting up a palette with the RColorBrewer package. I have tried using various values for the n: 5,6,7 (I am using 5 quantiles for my cuts) and even 1 to see if it would result in any observable change, but to no avail. I have also changed the choice of color several times but it also didn't bring any change.
I have also tried setting up a color function the colorRampPalette function but also unsuccessfully.
The data I'm using can be downloaded here (sorry, I couldn't figure out how to upload it with the question) : http://www.data.drees.sante.gouv.fr/ReportFolders/reportFolders.aspx, by typing "APL" in search bar and taking the first excel file (2015); apologies can't manage to link it properly either)
My code is the following:
library(maptools)
library(raster)
library(RColorBrewer)
library(readxl)
library(classInt)
apl15 <- read_excel("DATA USED")
france_com<- getData(name = "GADM",
country="FRA",
level=5)
paca <- subset(fr_com,NAME_1=="Provence-Alpes-Côte d'Azur")
apl15 <- data.frame(apl15)
names(apl15) <- c("code_com","name_com","apl","apl_young","pop_com","dept","apl*pop")
id_paca <- match(paca$NAME_5,apl15$name_com)
key_paca<- apl15[id_paca,"apl"]
paca$apl <- key_paca
apl.qt <- classIntervals(paca$apl,
n=5,
style="quantile")
br <- apl.qt$brks
offs <- 0.0000001
br[1] <- br[1] - offs
br[length(br)] <- br[length(br)] + offs
paca$apl_q <- cut(paca$apl,br)
display.brewer.all(type="seq")
my.palette <- brewer.pal(6, "OrRd")
spplot(paca,"apl_q",
col.region=my.palette,
main="APL en PACA", cex.=.7)
I expect this map but with colors corresponding to the palette I have selected.
my data mapped onto a region:
.
Thanks in advance for any help!

Related

Adding names on map using tmap/tmaptools [duplicate]

I'm trying to add some text labels a tmap plot.
library(tmap)
library(raster)
jnk <- getData("GADM",country="IND",level=2)
map_file <- tm_shape(jnk) +
tm_polygons() +
tm_text("NAME_1", remove.overlap = TRUE)
My problem is I'm getting duplicate text when I plot (can't post image since I'm new). I think I might have to group by some sort of geometry and NAME_1 combination but I'm unsure where to go from here.
Any advice would be great!
I am not certain what is your problem (as you were unable to post your image) but consider this code:
library(tmap)
library(raster)
jnk <- getData("GADM",country="IND",level=1)
tm_shape(jnk) + tm_polygons("NAME_1", legend.show = F) +
tm_text("NAME_1", size = 1/2)
I have made some minor changes to your code:
downloaded level 1 detail instead of level 2 detail (districts were too numerous, states are OK)
removed legend from the tm_polygons() call
made the letters of tm_text() smaller (to fit the north-eastern states)

Represent a colored polygon in ggplot2

I am using the statspat package because I am working on spatial patterns.
I would like to do in ggplot and with colors instead of numbers (because it is not too readable),
the following graph, produced with the plot.quadratest function: Polygone
The numbers that interest me for the intensity of the colors are those at the bottom of each box.
The test object contains the following data:
Test object
I have looked at the help of the function, as well as the code of the function but I still cannot manage it.
Ideally I would like my final figure to look like this (maybe not with the same colors haha):
Final object
Thanks in advance for your help.
Please provide a reproducible example in the future.
The package reprex may be very helpful.
To use ggplot2 for this my best bet would be to convert
spatstat objects to sf and do the plotting that way,
but it may take some time. If you are willing to use base
graphics and spatstat you could do something like:
library(spatstat)
# Data (using a built-in dataset):
X <- unmark(chorley)
plot(X, main = "")
# Test:
test <- quadrat.test(X, nx = 4)
# Default plot:
plot(test, main = "")
# Extract the the `quadratcount` object (regions with observed counts):
counts <- attr(test, "quadratcount")
# Convert to `tess` (raw regions with no numbers)
regions <- as.tess(counts)
# Add residuals as marks to the tessellation:
marks(regions) <- test$residuals
# Plot regions with marks as colors:
plot(regions, do.col = TRUE, main = "")

"Wasn't able to determine range of domain" for ColorNumeric

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.

Using a raster attribute from a multi-attribute raster for colour levels in a plot in R

I have a raster object with a large number of attributes, and I would like to plot the spatial data in R and colour code it by a certain attribute. I have not been able to work out how to use the information of a particular attribute to achieve this. So far I have successfully extracted the attribute of choice using factorValues(), but I cannot determine how to now incorporate this information into the plot() function. I tried using the ratify() and level() functions mentioned in the raster package documentation, but I don’t understand how the simplified online examples can be adapted for a raster with multiple attributes.
Any advice on how to achieve this would be greatly appreciated.
# read in shapefile
shp = readOGR(".", "grid")
#convert to raster
r = raster(extent(shp))
res(r) = c(1,0.5)
ra = rasterize(shp, r)
#crop raster to desired extent
rcrop = crop(ra, extent(-12, 2, 29, 51))
# extract attribute value of interest
f = factorValues(rcrop, 1:420, layer=1, att=17, append.names=FALSE)
# here there are 420 cells in the raster and I am interested in plotting values of attribute 17 of the raster (this is currently a numeric attribute, not a factor)
#extra code to set attribute as the level to use for plotting colours???
rcrop = ratify(rcrop)
rat = levels(rcrop)[[1]] #this just extras row IDs..not what I want
#…
### plot: I want to plot the grid using 7 colours (I would ideally like to specify the breaks myself)
require(RColorBrewer)
cols = brewer.pal(7,"YlGnBu")
#set breaks
brks = seq(min(minValue(rcrop)),max(maxValue(rcrop),7))
#plot
plot(rcrop, breaks=brks, col=cols, axis.arg=arg)
The following is pretty hacky (and may perform poorly for large rasters), but I'm not sure if there's a way to link col.regions to a specified attribute.
rasterVis::levelplot does a nice job of labelling colour ramps corresponding to factor rasters, and while it provides an att argument allowing you to specify which attribute you're interested in, this seems to only modify the labelling of the ramp. Raster cell values control how the colour ramp is mapped to the raster, so it seems to me that we need to modify the cell values themselves. Maybe #OscarPerpiñán will chime in here to prove me wrong :)
We can create a simple function to substitute the original cell values with whichever attribute we want:
switch_att <- function(r, att) {
r[] <- levels(r)[[1]][values(r), att]
r
}
Let's download and import a small example polygon dataset from Natural Earth:
library(rasterVis)
library(rgdal)
require(RColorBrewer)
download.file(file.path('http://www.naturalearthdata.com',
'http//www.naturalearthdata.com/download/110m/cultural',
'ne_110m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
shp <- readOGR(tempdir(), 'ne_110m_admin_0_countries')
rasterize the vector data:
r <- rasterize(shp, raster(raster(extent(shp), res=c(1, 1))))
And create some plots with levelplot:
levelplot(switch_att(r, 'continent'), col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
levelplot(switch_att(r, 'economy'), par.settings=BuRdTheme) +
layer(sp.polygons(shp, lwd=0.5))
EDIT
With Oscar's update to rasterVis, the switch_att hack above is no longer necessary.
devtools::install_github('oscarperpinan/rastervis')
levelplot(r, att='continent', col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
will produce the same figure as the first one above.

Clearing plotted points in R

I am trying to use the animation package to generate an "evolving" plot of points on a map. The map is generated from shapefiles (from the readShapeSpatial/readShapeLines functions).
The problem is when it's plotted in a for loop, the result is additive, whereas the ideal result is to have it evolve.
Are there ways of using par() that I am missing?
My question is: is there a way to clear just the points ploted from the points function
and not clearing the entire figure thus not having to regraph the shapefiles?
in case someone wants to see code:
# plotting underlying map
newyork <- readShapeSpatial('nycpolygon.shp')
routes <- readShapeLines('nyc.shp')
par(bg="grey25")
plot(newyork, lwd=2, col ="lightgray")
plot(routes,add=TRUE,lwd=0.1,col="lightslategrey")
# plotting points and save to GIF
ani.options(interval=.05)
saveGIF({
par(bg="grey25")
# Begin loop
for (i in 13:44){
infile <-paste("Week",i,".csv",sep='')
mydata <-read.csv(file = infile, header = TRUE, sep=",")
plotvar <- Var$Para
nclr <- 4
plotclr <-brewer.pal(nclr,"RdPu")
class<- classIntervals(plotvar,nclr,style = "pretty")
colcode <- findColours(class,plotclr)
points(Var$Lon,Var$Lat,col=colcode)
}
})
If you can accept a residual shadow or halo of ink, you can over-plot with color ="white" or == to your background choices. We cannot access your shape file but you can try it out by adding this line:
points(Var$Lon, Var$Lat, col="grey25")
It may leave gaps in other previously plotted figures or boundaries, because it's definitely not object-oriented. The lattice and ggplot2 graphics models are more object oriented, so if you want to post a reproducible example, that might be an alternate path to "moving" forward. I seem to remember that the rgl package has animation options in its repetoire.

Resources