Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set color for NA Value with spplot in R

Tags:

r

I'm trying to plot polygon data using function spplot from the sp package, but there are some missing values (NA) in my dataframe. When I plot this dataframe, missing values have a transparent color. I want to plot them in black. How can I do this?

library(sp)
spplot(TestData,12)

Here is my TestData object

like image 597
Nguyen Hoang Pham Avatar asked Jun 17 '15 09:06

Nguyen Hoang Pham


2 Answers

One way to achieve this is to use latticeExtra::layer_ to plot all polygons with your preferred NA colour, beneath the standard spplot.

library(latticeExtra)
spplot(TestData, 12, col.regions=heat.colors(101), at=seq(0, 4, length=100)) + 
  layer_(sp.polygons(TestData, fill='black'))

enter image description here

Similarly, if you have raster data, you can do the same with layer_ and grid.rect:

library(raster)
library(latticeExtra)
r <- raster(matrix(runif(100), ncol=10))
r[sample(100, 10)] <- NA

spplot(r, col.regions=grey.colors, at=seq(0, 1, length=100)) + 
  layer_(grid.rect(0, 0, 2, 2, gp=gpar(fill = 'lightblue')))

enter image description here

like image 127
jbaums Avatar answered Oct 30 '22 22:10

jbaums


I am using solution similar to jbaums', but I do it directly in the spplot function:

spplot(TestData, 12, col.regions=heat.colors(101), at=seq(0, 4, length=100),
    sp.layout = list(
        list("sp.polygons", TestData, first = TRUE, fill = "black")
    ) 
)

The sp.layout parameter allows to plot other spatial objects in the plot. So we plot the TestData polygon layer with black fill. The parameter first = TRUE says it is to be plot before the actual data - so it acts as a background. enter image description here

like image 1
Tomas Avatar answered Oct 30 '22 21:10

Tomas