Combining datasets: Counting Points in Polygon

Maps with a lot of dots are cool, but sometimes you’d like to count the number of things in a certain geographic area - maybe subway entrances per zip code, murders per neighborhood, etc.

This is a relatively common practice, and relatively easy. Sometimes you need a lot of processing power to get it done, but so it goes.

NOTE: So, this one works, but most people apparently use Vector > Data Management Tools > Join Attributes By Location! Points in Polygon is more useful when you have a lot of overlapping polygons.

Step One: Open Up Your Data

First, semi-obviously, you’ll need to open up your data in QGIS. Make sure they have the same CRS (what’s that?) - if not, change the CRS to match.

I’ve used a CSV of after-school programs for NYC and a shapefile of school districts. We’re going to be adding a column to count them up.

Opened up two layers

Make sure that your features overlap! If you don’t see any points in the same area as your shape, something probably went wrong with your CRS.

Step Two: Use Point In Polygon

Now use the top menu, and select Vector > Analysis Tools > Points In Polygon

Used points in polygon

Step Three: Fill in your options

Now let’s complete the Point in Polygon fields

  1. Your input vector layer is the shape - I’m using school districts.
  2. Your input point layer is your points - I’m using after-school programs.
  3. You aren’t aggregating any points - you’re just counting, so don’t select attributes to aggregate, and don’t select a statistical method to aggregate by.
  4. Name your new field. Sometimes I just stick with PNTCNT - for some terrible reason there’s a restriction on the length of the field name.
  5. You’ll want to add result to canvas - this will add it to the Layers once it’s complete.
  6. Click OK!
  7. Wait for it to finish, then click Close

Used points in polygon

When you’re combining a CSV and a shapefile, QGIS likes to complain about the CRS not matching even when it does match. If you get this error, you can probably ignore it.

Non-matching CRS

Step Four: Examine your new data

Right-click your brand-new layer, then select Open Attribute Table.

Used points in polygon

This will show you that your new shapefile contains not only the columns from before, along with any other columns it contains.

Used points in polygon

Step Five: Next steps

Maybe you’d like to learn how to color your map based on a column or aggregate some column of the points across the shapes?

Want to hear when I release new things?
My infrequent and sporadic newsletter can help with that.