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
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'))
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')))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With