Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
ArcGIS Pro

Count Polygons within Polygons in QGIS

How to Count Polygons within Polygons in QGIS

1. Introduction

Navigating the world of Geographic Information Systems (GIS) can often lead to intricate challenges, one of which is understanding how to count polygons within other polygons. This task, seemingly simple, holds significant importance in various geospatial analyses. Using QGIS, a leading open-source GIS software, we aim to demystify this process. Whether you’re charting urban zones, environmental regions, or any other spatial data, this guide will walk you through the essential steps, tools, and troubleshooting techniques to count polygons effectively within QGIS.

If you are working with QGIS you should listen to our podcast!

2. Understanding the Basics

What are Polygons in GIS?

Polygons are one of the core elements in Geographic Information Systems (GIS). At their essence, polygons are closed shapes used to represent areas on a map. This could range from natural features like lakes, forests, and islands to man-made structures or areas like cities, districts, and property plots. In GIS, polygons are not just static shapes; they come with attributes that provide more information about the area they represent, such as the name of a city or the type of vegetation in a forest.

Why is Counting Polygons within Polygons Important?

Imagine you’re an urban planner, and you have a map of a city divided into different zones (residential, commercial, etc.). Within these zones, you have individual plots or properties. If you wanted to know how many properties are in each zone, you’d essentially be counting polygons (properties) within other polygons (zones). This task is common in various fields, from environmental studies where one might want to count lakes within a particular region to business analytics where one might want to count outlets within different sales territories.

3. Setting Up Your Workspace

Importing Polygon Layers into QGIS:

Before diving into the analysis, it’s essential to have your data ready and accessible. Here’s how you can import your polygon layers:

  1. Open QGIS and start a new project.
  2. Navigate to the ‘Layer’ menu, select ‘Add Layer’, and then choose ‘Add Vector Layer’.
  3. Click on the ‘Browse’ button and locate your polygon file (common formats include .shp, .geojson, .kml, etc.).
  4. Select the file and click ‘Open’. Your polygon layer should now be visible on the QGIS canvas.

Georeferencing Your Data:

Ensuring your data is correctly georeferenced is crucial. Georeferencing means that your map layers will align correctly with their real-world locations.

  1. If your data isn’t georeferenced, go to the ‘Raster’ menu, select ‘Georeferencer’, and then ‘Open’.
  2. Add your map image and use control points to match the image’s locations with real-world coordinates.
  3. Once done, save the georeferenced data, and it should align correctly on the QGIS canvas.

Organizing Layers and Setting the View:

With multiple layers, organization is key:

  1. Use the ‘Layers Panel’ on the left to toggle the visibility of each layer.
  2. You can drag layers up or down in the panel to change their display order.
  3. Use the ‘Zoom’ and ‘Pan’ tools in the toolbar to adjust your view and focus on the area of interest.

Setting Layer Properties:

To make your analysis easier, it’s often helpful to adjust the visual properties of your layers:

  1. Right-click on a layer in the ‘Layers Panel’ and select ‘Properties’.
  2. Navigate to the ‘Symbology’ tab to adjust colors, fill patterns, and line styles.
  3. Use the ‘Labels’ tab if you want to display specific attribute data on the map, like polygon names or IDs.

By setting up your workspace efficiently, you ensure a seamless process as you move forward with your analysis. Proper organization and visualization can significantly impact the ease and accuracy of counting polygons within polygons.

4. Common Methods to Count Polygons within Polygons

a. Join Attributes by Location:

One of the most straightforward methods in QGIS to count polygons within polygons is using the “Join Attributes by Location” tool. Here’s how:

  1. Access the Tool: Navigate to the ‘Vector’ menu, select ‘Data Management Tools’, and then choose ‘Join Attributes by Location’.
  2. Set Parameters:
  • Target Layer: This should be the layer containing the larger polygons (e.g., zones).
  • Join Layer: This is the layer with the smaller polygons you want to count (e.g., properties).
  • Geometric Predicate: Choose “Contains” to ensure the smaller polygons are entirely within the larger ones.
  • Joined Table: Opt for “Keep All Records” to ensure all polygons, even those without any contained polygons, are included in the results.
  1. Run the Tool: Once set, run the tool. The resulting layer will have an added attribute showing the count of contained polygons for each larger polygon.

b. Intersection Tool:

The Intersection Tool can be particularly useful when you want to see which smaller polygons lie within each larger polygon.

  1. Access the Tool: Go to the ‘Vector’ menu, select ‘Geoprocessing Tools’, and then ‘Intersection’.
  2. Set Parameters:
  • Input Layer & Overlay Layer: Input both your polygon layers.
  1. Run the Tool: The resulting layer will show intersections of the smaller polygons with the larger ones. The attribute table will contain attributes from both layers, allowing for easy counting.

c. Using Centroids:

For a more visual approach, converting polygons to their centroids can be helpful.

  1. Create Centroids: Navigate to ‘Vector’ > ‘Geometry Tools’ > ‘Centroids’. Choose the smaller polygon layer to convert.
  2. Count Points in Polygon: Now, use the ‘Vector’ > ‘Analysis Tools’ > ‘Count Points in Polygon’ tool. The larger polygons will be your input layer, and the centroids will be the points layer.
  3. Review Results: The resulting layer will have an added attribute showing the count of centroids (and by extension, the original polygons) within each larger polygon.

Each of these methods has its advantages, depending on the specifics of your data and what you aim to achieve. It’s always a good idea to familiarize yourself with all of them, so you can choose the most suitable one for your project.

5. Troubleshooting Common Issues

Boundary Precision Problems:

One of the most common issues users face is discrepancies due to boundary precision.

  • Solution: Consider using a buffer with a very small distance to slightly expand or contract polygon boundaries. This can help in ensuring that polygons that are supposed to touch or overlap do so correctly.

Ensuring Correct Layer Selection:

It’s easy to mistakenly select the wrong layer, especially when dealing with multiple layers.

  • Solution: Always double-check the layers you’ve selected before running any tools. Naming your layers descriptively can also help in avoiding such mistakes.

Dealing with Overlapping Polygons:

Sometimes, smaller polygons might overlap two or more larger polygons, leading to counting discrepancies.

  • Solution:
  1. Use the ‘Split Features’ tool to divide overlapping polygons based on the boundaries of the larger polygons.
  2. After splitting, recount the polygons using the methods mentioned in Section 4.

Incorrect Count Due to Projection Issues:

Different layers might be in different coordinate reference systems (CRS), leading to misalignment and incorrect counts.

  • Solution:
  1. Check the CRS of both layers by right-clicking on the layer and selecting ‘Properties’ > ‘Source’.
  2. If they differ, reproject one of the layers to match the other using the ‘Reproject Layer’ tool found under ‘Vector’ > ‘Data Management Tools’.

Missing Polygons in the Output:

Sometimes, after performing an operation, not all polygons appear in the output.

  • Solution: Ensure that when using tools like “Join Attributes by Location,” the option “Keep All Records” is selected. This ensures that even polygons without any contained polygons are included in the results.

Troubleshooting is an integral part of any GIS task. Being aware of common issues and their solutions can save a lot of time and ensure the accuracy of your results. Always remember to keep backups of your original data before making any modifications, allowing you to revert and try a different approach if needed.

6. Advanced Tips and Tricks

Leveraging Plugins for Enhanced Functionality:

QGIS’s open-source nature means there’s a plethora of plugins available that can simplify or automate many tasks.

  • Recommended Plugin: The ‘RefFunctions’ plugin adds several functions that can be used in the Field Calculator, including one that counts the number of features from one layer that are within features of another layer.

Scripting and Automation for Large Datasets:

For those dealing with extensive datasets, manual methods might be time-consuming.

  • PyQGIS: Dive into the world of PyQGIS, QGIS’s Python library. With a bit of scripting, you can automate the counting process, especially useful for repetitive tasks or large datasets.

Using Expressions for Complex Queries:

QGIS’s Expression Builder is a powerful tool that allows for more nuanced queries and operations.

  • Example: If you want to count only specific polygons within another (e.g., only residential properties within a zone), you can use expressions to filter your data before counting.

Virtual Layers for Dynamic Analysis:

Virtual layers allow you to create a new layer based on SQL queries from existing layers, making them perfect for dynamic analysis.

  • Usage: Instead of creating a permanent new layer every time you count polygons, use a virtual layer to get a real-time count, especially useful if your data changes frequently.

Optimizing Performance for Faster Analysis:

Large datasets can slow down QGIS. Here are some tips to ensure smoother performance:

  1. Render Optimization: Turn off rendering (using the “Render” button at the bottom) while performing operations.
  2. Use Spatial Indexes: Spatial indexes, like R-trees, can speed up spatial queries significantly.
  3. Limit the Number of Displayed Features: Use the “Filter” option in layer properties to display only the features you’re currently working with.

Advanced users of QGIS often find that the software’s true power lies in its flexibility and extensibility. By exploring beyond the basic tools and diving into scripting, expressions, and plugins, you can significantly enhance your productivity and tackle more complex geospatial challenges with ease.

7. Conclusion

As we wrap up our exploration into counting polygons within polygons in QGIS, it’s evident that the software offers a plethora of tools and methods to tackle this common geospatial challenge. Whether you’re a beginner just getting started with GIS or a seasoned professional, understanding the intricacies of these methods is crucial for accurate and efficient analysis.

Key Takeaways:

  1. Multiple Methods: QGIS provides several tools, from “Join Attributes by Location” to the “Intersection Tool,” each with its unique advantages depending on the specifics of your data.
  2. Troubleshooting is Essential: As with any software, challenges can arise. Being proactive in identifying common issues and knowing how to address them can save significant time and ensure the accuracy of your results.
  3. Advanced Capabilities: For those looking to delve deeper, QGIS offers advanced functionalities through scripting, plugins, and expressions, allowing for more complex and dynamic analyses.

About the Author
I'm Daniel O'Donohue, the voice and creator behind The MapScaping Podcast ( A podcast for the geospatial community ). With a professional background as a geospatial specialist, I've spent years harnessing the power of spatial to unravel the complexities of our world, one layer at a time.

Leave a Reply