[GRASS-user] Alternative to r.stats to generate % of surface

Marcello Gorini gorini at gmail.com
Tue Nov 15 07:35:50 EST 2011

Hi Helena,

I have come to the same problem and solved it with ugly and very specific
shell scripts. There is most certainly a better way within GRASS and no
doubt you can code it much better in Shell, but anyway, this may get you
going somehow.

Code snippet:


g.region rast=$MAP
rm $file

tot=$(r.univar $MAP | grep "^n: " | awk '{print $2}')
r.stats -cn $MAP > stats.txt

while [ $cats -le $max_cats ]; do

    ncat="`head -$cats stats.txt | tail -1 | awk '{print $2}'`"
    cat="`head -$cats stats.txt | tail -1 | awk '{print $1}'`"
    perc="`echo $tot $ncat | awk '{printf("%.5f", $2 / $1 * 100);}'`"

    echo $cat $perc >> $file

    cats="$(expr $cats + 1)"


I wanted everything in text files, so I generated these stats.txt and
true_percentages.txt. The idea of the script is to use the actual cell
count given by r.stats -cn and divide it by the total count given by

Note that this script is very specific and only work for categories that
are incremented by 1. In my case, they go from 1 to 9.

How brave I am to publicize such an ugly script, huh? :) The result sums up
to 1 at least. Just give the name of the categorical map as input.

Hope it helps somehow.


On Tue, Nov 15, 2011 at 9:36 AM, Helena Herrera <helenaherrera1980 at gmail.com
> wrote:

> Greetings
> I want to calculte % of surface in a raster map for each Integer class
> value. The thing is that I'm, using r.stats but the sum % values is always
> much more (104 or 102 or 105). Is there any other (more precised) method to
> calculate this ?
> THanks
> Helena
> _______________________________________________
> grass-user mailing list
> grass-user at lists.osgeo.org
> http://lists.osgeo.org/mailman/listinfo/grass-user
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/grass-user/attachments/20111115/83ac87b5/attachment.html

More information about the grass-user mailing list