0

I have a classified raster containing 12 classes named "1", "2", "3", etc. representing the land use. I have a second raster containing some values representing the evapotranspiration rate. I am trying to create a boxplot for the evapotranspiration rate for the classes 2 and 10.

I was able to create boxplots but they contain all the classes but I only want to get the classes 2 and 10.

Below the code with: r, the classified raster containing 12 classes and evapo, the raster containing the evapotranspiration values

 boxplot(evapo, r)

Any help would be great!

armin
  • 77
  • 8

3 Answers3

1
library(raster)
library(ggplot2)
library(dplyr)
r <- raster(nc=10, nr=5)
r[] <- runif(ncell(r), min=10, max=20) * 2
#plot(r)
s <- setValues(r,
               sample(c(1:4), replace = T, size=50)
               )
plot(s)
ct <- crosstab(r,s, useNA=TRUE, long=TRUE)
ct2 <- ct[ rep( seq(dim(ct)[1]), ct$Freq), ]

ggplot(filter(ct2, layer.2 %in% c(1,2)), aes(y=as.numeric(layer.1), x=layer.2)) +
  geom_boxplot()

enter image description here

Paulo E. Cardoso
  • 5,778
  • 32
  • 42
1

Here is a variation on Paulo's solution

library(raster)
r <- raster(nc=10, nr=5)
r[] <- runif(ncell(r), min=10, max=20) * 2
s <- setValues(r, sample(c(1:4), replace = T, size=50))

rs <- stack(r, s)
names(rs) <- c('r', 's')

d <- as.data.frame(rs)
# all classes
boxplot(r~s, data= d)
# only class 2 and 4
boxplot(r~s, data=d[d$s %in% c(2,4), ])

If you cannot make d because the rasters are too large, you could take a large sample instead for an approximate result

n <- 10000
d <- data.frame(sampleRegular(rs, n))
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
0

Without being able to see your dataset I can not be certain this solution will work for you, but this should help you out.

boxplot(evapo[which(class == 2 | 10)], r[which(class == 2 | 10)])

Alternatively you can generates 'new' raster from your evapo and r, which only contain information where the classes are 2 and 10, then run a boxplot with those.

R Nubsekov
  • 11
  • 4