Did you ever add a legend to your categorical raster map in GRASS GIS that displayed many more categories than your map actually has? It can happen if that map was ‘cut out’ from a larger region using r.mapcalc. For example, if I have a vegetation map of eastern Africa, and I need one for Rwanda only. I would do something like:
g.region vector=Rwanda r.mask -a vector=Rwanda r.mapcalc "Rwanda_example = veg_east_Africa"
Now, when I display the map and add the legend, it’ll show all original categories of the veg_east_Africa map.
Thanks to the ever helpful people on the GRASS email list, I quickly found out that GRASS copies over all the categories of the original map to the category table¹ of the new map. Not sure if there is any particular reason for that, but there is an easy work around:
r.category Rwanda_example | r.category Rwanda_example rules=-
This effectively removes all categories not present in the map. Now you can add the legend again, but this time make sure to use the option to ‘skip categories with no label’.
Why using the ‘skip categories with no label’, didn’t we just remove the redundant categories? Well, as it turns out, when creating the new map, not only all categories are copied over, but also the colour table of the original map. This actually makes sense, especially when working with raster layers with continuous values. However, it is not what I normally want for categorical maps. Thus, how to trim the colour table so it only contains colour definitions for the values present in the new map? Again from the GRASS email list, the simplest way is probably something like:
r.colors.out map | command | r.colors map rules=-
where “command” is a function (e.g., using grep, sed or similar command line tools) to filters the colour rule. To make life easier, I wrote a small python script, which basically does just that, filtering out all colour rules for categories that are not present in the map.
Main lesson learned? That would probably be that if you have a problem in GRASS, help is often just one email away 🙂