R - stuck with plot() - Colouring shapefile polygons based upon a slot value

后端 未结 1 1389
傲寒
傲寒 2020-12-19 04:50

I have a shapefile showing remote areas in Australia, obtained from the Australian Bureau of Statistics:

http://www.abs.gov.au/AUSSTATS/abs@.nsf/DetailsPage/1270.0.5

相关标签:
1条回答
  • 2020-12-19 05:38

    You did all the work already!

    plot(ra, col=ra@data$COLOUR)
    

    Or even, as @Spacedman suggested:

    plot(ra, col=ra$COLOUR)
    

    And that's it!

    enter image description here

    And if you want to get rid of the polygon borders:

    plot(ra, col=ra$COLOUR, border=NA)
    

    enter image description here

    Edit: an attempt to explain this behaviour:

    According to ?SpatialPointsDataFrame:

    SpatialPolygonsDataFrame with default ID matching checks the data frame row names against the Polygons ID slots. They must then agree with each other, and be unique (no Polygons objects can share IDs); the data frame rows will be re-ordered if needed to match the Polygons IDs..

    Meaning that the polygons are ordered according to their ID and hence are in the order of the rows of the dataframe in the slot @data.

    Now if you look at the function plot.SpatialPolygons (using getAnywhere(plot.SpatialPolygons)) there are those lines at some point:

    ...
        polys <- slot(x, "polygons")
        pO <- slot(x, "plotOrder")
        if (!is.null(density)) {
            if (missing(col)) 
                col <- par("fg")
            if (length(col) != n) 
                col <- rep(col, n, n)
            if (length(density) != n) 
                density <- rep(density, n, n)
            if (length(angle) != n) 
                angle <- rep(angle, n, n)
            for (j in pO) .polygonRingHoles(polys[[j]], border = border[j], 
                xpd = xpd, density = density[j], angle = angle[j], 
                col = col[j], pbg = pbg, lty = lty, ...)
        }
    ...
    

    The vector inputted to col has the same order as the polygons slot and hence as ID. plotOrder is used to index all of them in the same way.

    0 讨论(0)
提交回复
热议问题