spplot legend with point rather than with scale - r

I am creating a plot based on INLA predictions. Everything works perfectly for the modelling, but for the plot,the legend on the graph are points (like https://gis.stackexchange.com/questions/350918/how-do-i-reverse-spplot-colour-key-so-the-values-are-decreasing) rather than a scale (like here http://www.nickeubank.com/wp-content/uploads/2015/10/RGIS3_MakingMaps_part1_mappingVectorData.html):
And here is the code that I would like to change. I guess there is a problem of factor (R spplot: colorbar rather than legend for SpatialPoint data, spplot issue with legend range and colors distribution) but I cannot understand how/what to change:
m_grid <- inla(formWITHOUT, data = inla.stack.data(region.stack.predGrid, spde = inlaSetting$region.spde),
family = "gamma",
control.predictor = list(A = inla.stack.A(region.stack.predGrid), compute = TRUE, link=1),
control.compute = list(cpo = TRUE, dic = TRUE),
control.family=list(link="default"))
summary(m_grid)
index.pred <- inla.stack.index(region.stack.predGrid, "region.pred")$data
region.grid_sf$Sbiomass <- m_grid$summary.fitted.values[index.pred, "mean"]
region.grid_sf$Sbiomass_sd <- m_grid$summary.fitted.values[index.pred, "sd"]
my.palette <- brewer.pal(n = 7, name = "OrRd")
par(mar = c(0,0,0,0))
spplot(region.grid_sf, c("Sbiomass"), col.regions = my.palette, col = "transparent")
Thanks in advance for any tips !

I finally found the answer:
cuts <- c(0,5000,10000,15000,20000,25000,30000)
spplot(region.grid_sf,
c("Sbiomass"),
col.regions = my.palette,
col = "transparent",
key.space = list(x=0.1,y=0.3),
colorkey =T,
cuts = cuts,
cex = 2,
pch = 22)

Related

Why do the error occurs adding legend to plot?

I'm trying to add the legend to my classification map using the code below.
library(raster)
library(RStoolbox)
landsat5 <- stack('lt05.tif')
shp<-shapefile("to5/to.shp")
SC_rf <- superClass(landsat5, shp, responseCol = "MC_ID",
nSamples = 1000, polygonBasedCV = TRUE,
model = "rf", tuneLength = 5, kfold = 5,
mode = "classification", predType = "raw", overwrite = TRUE)
## Plots
colors <- c("yellow", "green", "deeppink", "orange", "red")
plot(SC_rf$map, col = colors, legend = TRUE, axes = FALSE, box = FALSE)
legend(1, 1, legend = levels(shp$MC_info), fill = colors , title = "Classes")
The map is created but a legend error occurs:
'legend(1, 1, legend = levels(shp$MC_info), fill = colors, title = "Classes")':
'legend' is of length 0
Here is my shp object:
MC_info seems to be a vector, not a factor, so you don't need to use levels(). To access data in shapefile object, try to convert it by as.data.frame() function from raster package:
legend(1, 1, legend = raster::as.data.frame(shp)$MC_info, fill = colors , title = "Classes")
Or you can define a variable for that:
shp_df <- raster::as.data.frame(shp)
legend(1, 1, legend = shp_df$MC_info, fill = colors , title = "Classes")
This works for me as it converts the data data frame from the shp object and the MC_Info column is easily accessible. But I don!t have your data to check the legend working properly as you need...

contourplot color and labels options in Lattice for R

I am quite new to Lattice and I am stuck with some possibly basic coding. I am using shapefiles and geoTIFFS to produce maps of animals distribution and in particular I have:
1 x point shapefile
2 x geoTIFF
1 x polygon shapefile
I am overlapping a levelplot of one of the geoTIFF (UD generated with adehabitatHR) with a contourplot of the same geoTIFF at specific intervals (percentile values), a contourplot of the second geoTIFF (depth raster from ETOPO2) for three specific values (-200, -1000 and -2000), the point shapefile (animal locations) and the polygon shapefile (land). All works fine but I need to change the font size of contour plot labels, their length (i.e. from 0.12315 to 0.123) and positioning for all the contourplots. For the depth contourplot I would like to change the style of each line in something like "continous line", "dashed line" and "point line", and for the contourplot of the UD I would like to change the color of each line using a yellow to red palette.
As far as I understand, I should use panel functions to implement these changes (e.g. Controlling z labels in contourplot) but i am not quite sure how to do it. Part of my code to generate the "plot":
aa <-
quantile(
UD_raster,
probs = c(0.25, 0.75),
type = 8,
names = TRUE
)
my.at <- c(aa[1], aa[2])
depth<-c(-100, -200, -2000)
levelplot(
UD_raster,
xlab = "",
ylab = "",
margin = FALSE,
contour = FALSE,
col.regions = viridis(100),
main = "A",
maxpixels = 2e5
) + layer(sp.polygons(Land, fill = "grey40", col = NA)) + layer(sp.points(locations, pts = 2, col = "red")) + contourplot(
UD_raster,
at = my.at,
labels = TRUE,
margin = FALSE
) + contourplot(
ETOPO2,
at = depth,
labels = TRUE,
margin = FALSE
)
A simplified image, with no UD layer and no point shapefile can be found here and as you can see it is pretty messy. Thanks for your help.
So far for the ETOPO2 countourplot I have solved by eliminating the labels and adding the argument lty to style the line. Because I can't figure out how to use lty with different values for each single line in my contour, I have replicated the contourplot function three times on the same surface, one for each contour I am interested into (this was easy because I only need three contours).
For the position, font and font size of the labels of the remaining contourplot I have used
labels = list(cex = 0.8, "verdana"),
label.style = "flat"
To "shorten" the length of the labels I have used the function round where I specify to which decimal digit to round number.
So now my new code looks like:
aa <-
quantile(
UD_raster,
probs = c(0.25, 0.75),
type = 8,
names = TRUE
)
my.at <- c(aa[1], aa[2])
my.at <- round(my.at, 3)
levelplot(
UD_raster,
xlab = "",
ylab = "",
margin = FALSE,
contour = FALSE,
col.regions = viridis(100),
main = "A",
maxpixels = 2e5
) + layer(sp.polygons(Land, fill = "grey40", col = NA)) + layer(sp.points(positions, pts = 2, col = "red")) + contourplot(
UD_raster,
at = my.at,
labels = list(cex = 0.8, "verdana"),
label.style = "flat",
margin = FALSE
) + contourplot(
ETOPO2,
at = -200,
labels = FALSE,
margin = FALSE,
lty = 1,
pretty = TRUE
) + contourplot(
ETOPO2,
at = -1000,
labels = FALSE,
margin = FALSE,
lty = 2,
pretty = TRUE
) + contourplot(
ETOPO2,
at = -2000,
labels = FALSE,
margin = FALSE,
lty = 3,
pretty = TRUE
)
As one could expect, it takes a bit longer to produce the plot. Still no idea on how to change the colors of the UD contourplot.

How to get the full size picture of graph that plotted in R

I have plotted a histogram graph but it show that the graph has been cut a part like the image show. Is there any solution to solve it?
#install.packages("RegressionFactory")
#install.packages("MASS")
#install.packages("qpcR")
#install.packages("olsrr")
#install.packages("car")
#install.packages("ggplot2")
library(RegressionFactory)
library(MASS)
library(qpcR)
library(olsrr)
library(car)
library(openxlsx)
library(ggplot2)
dataset=read.csv(file.choose(),header=T)
attach(dataset)
View(dataset)
hist(dataset$CGPA,
freq = FALSE,
main = "Chance of admit vs CGPA",
xlab = "CGPA",
ylab = "Chance of admit",
las = 1,
col = c("skyblue")
)
lines(density(dataset$CGPA), lwd = 4, col = "red")
You need to provide appropriate limits to the y-axis
set.seed(53)
dat = rnorm(500)
d = density(dat)
hist(dat, ylim = c(0, max(d$y)), freq = FALSE)
lines(d)

How to edit the legend of a scatter plot?

I made a plot with legend. By this code:
scatter3d(x = red, y = green, z = blue, groups = C1class$V1, surface. col = 1:21,
grid = FALSE, surface = FALSE)
legend3d("right", legend = levels(C1class$V1),
col = rainbow(21), pch = 16, inset = -0.25, xpd = TRUE)
But my graph looks like this:
How can I edit it to look better?
Can you help me with some function to fix it?
Thanks for you help.
You do not provide your data, so I cannot test your problem exactly,
but I think that the example below will help you solve your problem.
I think that your problem stems from including the parameter inset = -0.25.
That is shifting the legend out of the display area. Looking at your picture,
I think that the reason that you did that is because otherwise the
legend covers over part of the scatterplot. A different way to fix this is to adjust the drawing area using windowRect to allow more space.
A plot like yours with the legend chopped off.
scatter3d(x = iris[,1], y = iris[,2], z = iris[,3], groups = iris[,5],
surface.col = rainbow(3), grid = FALSE, surface = FALSE)
legend3d("right", legend = levels(iris[,5]),
col = rainbow(3), inset = -0.25, pch = 16, xpd = TRUE)
A second plot without the indent. Now the legend overlaps the plot.
scatter3d(x = iris[,1], y = iris[,2], z = iris[,3], groups = iris[,5],
surface.col = rainbow(3), grid = FALSE, surface = FALSE)
legend3d("right", legend = levels(iris[,5]),
col = rainbow(3), pch = 16, xpd = TRUE)
Finally, the window size is adjusted to allow more room for the legend.
par3d(windowRect = c(100, 100, 600, 350))
scatter3d(x = iris[,1], y = iris[,2], z = iris[,3], groups = iris[,5],
surface.col = rainbow(3), grid = FALSE, surface = FALSE)
legend3d("right", legend = levels(iris[,5]),
col = rainbow(3), pch = 16, xpd = TRUE)
You may need to adjust the windowRec differently for your data, but this setting will be a good place to start.

R: plot circular histograms/rose diagrams on map

I am trying to plot rose diagrams/ circular histograms on specific coordinates on a map analogous to drawing pie charts on a map as in the package mapplots.
Below is an example generated with mapplots (see below for code), I'd like to replace the pie charts with rose diagrams
The package circular lets me plot the rose diagrams, but I am unable to integrate it with the mapplots package. Any suggestions for alternative packages or code to achieve this?
In response to the question for the code to make the map. It's all based on the mapplots package. I downloaded a shapefile for the map (I think from http://www.freegisdata.org/)
library(mapplots)
library(shapefiles)
xlim = c(-180, 180)
ylim = c(-90, 90)
#load shapefile
wmap = read.shapefile ("xxx")
# define x,y,z for pies
x <- c(-100, 100)
y <- c(50, -50)
z1 <- c(0.25, 0.25, 0.5)
z2 <- c(0.5, 0.2, 0.3)
z <- rbind(z1,z2)
# define radii of the pies
r <- c(5, 10)
# it's easier to have all data in a single df
plot(NA, xlim = xlim, ylim = ylim, cex = 0.75, xlab = NA, ylab = NA)
draw.shape(wmap, col = "grey", border = "NA")
draw.pie(x,y,z,radius = r, col=c("blue", "yellow", "red"))
legend.pie (x = -160, y = -70, labels = c("0", "1", "2"), radius = 5,
bty = "n", cex = 0.5, label.dist=1.5, col = c("blue", "yellow", "red"))
the legend for the pie size can then be added using legend.bubble
Have a look at this example, you can use the map as background an plot your rose diagrams withPlotrix or ggplot2. In either case you would want to overlay multiple of these diagrams on top of your map which is easy to do in ggplot, just have a look at the example.
I discovered subplot() in the package Hmisc, which seems to do exactly what I wanted. Below is my solution (without the map in the background, which can be plotted using mapplots). I am open to suggestions on how to improve this though...
library(Hmisc)
library (circular)
dat <- data.frame(replicate(2,sample(0:360,10,rep=TRUE)))
lat <- c(50, -40)
lon <- c(-100, 20)
# convert to class circular
cir.dat <- as.circular (dat, type ='angles', units = 'degrees', template = 'geographic', modulo = 'asis', zero = 'pi/2', rotation = 'clock')
# function for subplot, plots relative frequencies, see rose.diag for how to adjust the plot
sub.rose <- function(x){
nu <- sum(!is.na(x))
de <- max(hist(x, breaks = (seq(0, 360, 30)), plot = FALSE)$counts)
prop <- nu/de
rose.diag(x, bins = 12, ticks = FALSE, axes = FALSE,
radii.scale = 'linear',
border = NA,
prop = prop,
col = 'black'
)
}
plot(NA, xlim = xlim, ylim = ylim)
for(i in 1:length(lat)){
subplot(sub.rose(cir.dat[,i]), x = lon[i], y = lat[i], size = c(1, 1))
}

Resources