Monday 23 May 2016

QGIS How to label individual sides of polygon



Using native QGIS layer property definitions, I have successfully labelled each polygon in my layer with its area and perimeter.


Never satisfied, I now wish to label each side of each polygon with its length.


It would seem to be a common-enough requirement but I'm not getting good hits.



Answer



The "networks" plugin in QGIS has a facility to split polygons into individual line segments which you can then label with length. I discovered this by trying various search terms in the plugin installer menu. Searching for "split" there did the trick. Install "networks" from the plugins menu.


First convert your polygons to lines using the standard "Vector -> Geometry Tools -> Polygons to Lines" menu option, creating a new shapefile and layer in the process. This won't touch your polygons.


Then select the new lines layer, turn editing on via the pencil icon, and select all the features, then run the "Vector -> Networks -> Split" item. Now you have many line segments! Turn editing off, and save the changes.


Turn on labelling, and use $length for the label. There were too many decimals when I first did this, so I used substr($length, 1, 4) to get this:


labelled line segment lengths


You could also use round($length, 2) for the same effect, but if your line lengths are in thousands or millions of units then you'll still get long labels. You could scale them by 1000000 in the labelling expression, but you will have difficulty getting consistent length labels if your line lengths span several orders of magnitude. It is possible to write a custom python function for formatting numbers in scientific notation to a constant width, and I've just done that and it looks okay.



If you give your line layer an invisible line style then you'll just get your polygon styling with labels on the edges.


enter image description here


Note the 0.37 and 0.10 on the upper left feature seem to be labelling the same side, but that's because there's a node splitting that line. If this is a problem with your case then I suspect a generalisation with a very small, or even zero, tolerance should be enough to remove nodes where you have perfectly straight sides defined by more than one line segment. You can map the nodes of your polygons by using "Vector -> Geometry Tools -> Extract Nodes" to create a point shapefile if you can't see where they are.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...