Apatura
Apatura

Reputation: 65

Raster Plotting with Grayscale: both 0 and 1 are plotted in white

I have the following example code:

library(raster)
library(SpaDES)

m = matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1, 0,
         0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
         0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5),nrow=4,
         ncol=10, byrow=TRUE )
r <- raster(m)
Plot(r, cols = grey.colors(10, start=0, end=1), title = "4x10 Raster")

This should produce a 4x10 Raster, where each 0 represents a black square, a 1 a white square and the other numbers gray squares. Unfortunately, both one and zero (as well as the background) are white. How can I get the zeros to appear as a black square?

Raster with white instead of black

Edit: I am using the R package "SpaDES" for ecological applications, Plot is a function from that package. It is very important that the raster squares are plotted as squares no matter the shape of the plot viewer or the size of the raster, since it represents a rastered map.

Thank you for your help.

Upvotes: 0

Views: 2231

Answers (3)

Apatura
Apatura

Reputation: 65

So the way to solve my problem while still using the Plot function of the SpaDES package instead of plot seems to be the following:

library(raster)
library(SpaDES)

m = matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1, 0,
         0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
         0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5),nrow=4,
       ncol=10, byrow=TRUE )
r <- raster(m)

Plot(r, cols = grey.colors(10, start=0, end=1), title = "4x10 Raster", na.color = "black")

raster plot with zeros plotted in black

I still don't understand why changing options for zero.color does not work. Here are the definitions from the Plot function from SpaDES:

na.color    Character string indicating the color for NA values. Default transparent.
zero.color  Character string indicating the color for zero values, when zero is the minimum value, otherwise, zero is treated as any other color. Default transparent.

Upvotes: 0

derive111
derive111

Reputation: 143

From @Derek Corcoran's correction. I add some code to preserve the aspect ratio of the raster.

library(raster)
library(SpaDES)
m = matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1, 0,
             0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
             0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5),nrow=4,
           ncol=10, byrow=TRUE )
r <- raster(m)
#the aspect ratio should be modified to "0.4". 
plot(r,asp=0.4,col = grey.colors(10, start=0, end=1))
#Because it is the relation beetween columns and rows.

enter image description here

Upvotes: 0

Derek Corcoran
Derek Corcoran

Reputation: 4092

I did this:

plot(r, col = grey.colors(10, start=0, end=1), main = "4x10 Raster")

and got this:

enter image description here

Changed Plot to plot, cols to col, and title to main.

Upvotes: 3

Related Questions