Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to legend a raster using directly the raster attribute table and displaying the legend only for class displayed in the raster?
    primarykey
    data
    text
    <p>I would like to use the raster attribute table information to create the legend of a raster such as the raster <a href="https://i.stack.imgur.com/tgC2P.png" rel="nofollow noreferrer">1</a> and display the legend only for the class displayed in the raster. I build an example to explain what I would like to get.</p> <p><strong>1/ Build the raster</strong></p> <pre><code>r &lt;- raster(ncol=10, nrow=10) values(r) &lt;-sample(1:3,ncell(r),replace=T) </code></pre> <p><strong>2/ Add the Raster Attribute Table</strong></p> <pre><code>r &lt;- ratify(r) # build the Raster Attibute table rat &lt;- levels(r)[[1]]#get the values of the unique cell frot the attribute table rat$legend &lt;- c('Class A', 'Class B', 'Class C') levels(r) &lt;- rat </code></pre> <p><strong>3/ Plot the raster</strong> Fig <a href="https://i.stack.imgur.com/tgC2P.png" rel="nofollow noreferrer">1</a></p> <pre><code>my_col=c('blue','red','green') plot(r,col=my_col,legend=F,box=F,axes=F) legend(x='top', legend =rat$legend,fill = my_col) </code></pre> <p>I would like to replace the <code>legend =rat$legend</code> parammeter by a properties of the raster linked to the ratser attribute table. I have tried different combination using <code>levels()</code> such as <code>c(levels(r)[[1]][1])</code> but I generate a list and not a character not usable in the legend parameter.</p> <p><strong>4/ Crop and plot the raster to a part with only 2 classes (here the 4 pixels at the down right extent)</strong> Fig <a href="https://i.stack.imgur.com/VzF8M.png" rel="nofollow noreferrer">2</a></p> <pre><code>rcrop&lt;-crop(r,extent(r,9,10,9,10)) plot(rcrop,col=my_col,legend=F,box=F,axes=F) </code></pre> <p>For this second fig, I thus would like to diplay automatically only the legend of the class displayed on the raster <a href="https://i.stack.imgur.com/VzF8M.png" rel="nofollow noreferrer">2</a>.</p> <p><img src="https://i.stack.imgur.com/VzF8M.png" alt="Raster with legend"></p> <p><img src="https://i.stack.imgur.com/tgC2P.png" alt="Cropped raster with legend"></p> <hr> <p>Here is the solution proposed by Roman <a href="https://i.stack.imgur.com/hAJdN.png" rel="nofollow noreferrer">4</a>. <img src="https://i.stack.imgur.com/hAJdN.png" alt="Solution proposed by Roman"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload