[R-sig-Geo] Unexpected result from rasterVis::levelplot
oscar.perpinan at gmail.com
Fri Jun 27 13:39:28 CEST 2014
> I was expecting that levelplot would produce a legend in which the each
> level of the attribute used in the plot was listed once ( and associated
> with a single color in the legend).
> However levelplot is resulting in one level in the legend for each of the
> RAT IDs.
Right, this is what levelplot is supposed to produce. The levels of
your Raster are the unique cell values, and they are defined by the
first column of the RAT. The help page of 'ratify' explains that: "a
RasterLayer is linked to other values via a "Raster Attribute Table"
(RAT). Thus the cell values are an index, whereas the actual values of
interest are in the RAT. The RAT is a data.frame. The first column in
the RAT ("ID") has the unique cell values of the layer; this column
should normally not be changed. The other columns can be of any basic
type (factor, character, integer, numeric or logical)"
Therefore, I can't see any other solution than substituting the values
of your cells using 'subs', 'reclassify', etc.
On the other hand, it is not good practice to access and modify the
slots directly using @. Instead you should use the methods defined in
the package (for example,
In this case you should use "levels" and "levels<-":
## Here I assume that R has three levels (three unique cell values)
R <- ratify(R)
rat <- levels(R)[]
rat$alpha <- c("a","b","c")
rat$alphakey <- c(1,2,3)
levels(R) <- rat
> Additionally where the attribute had NA values I expected that these would
> result in a the corresponding cells appearing blank (as NA values in the
> original raster did) however a color is assigned to the "NA" from the
> attribute table and it appears in the legend, but the NA cells in the
> raster istself remain blank.
You have to substitute the NA cells with a value if you need them to
be included in the RAT as a different level.
> grid.arrange(p1,p2,p3,p4,nrow=2, ncol=2)
Last, you can arrange the graphic using lattice::print.trellis instead
print(p1, split = c(1, 1, 2, 2), more = TRUE)
print(p2, split = c(1, 2, 2, 2), more = TRUE)
print(p3, split = c(2, 1, 2, 2), more = TRUE)
print(p4, split = c(2, 2, 2, 2))
More information about the R-sig-Geo