I have two shapefiles: "States" - contains polygons for the 50 US states, and "Widget_stores" - contains points where widget stores are located. I want to adjust the symbology of "States" to change colors based on the number of stores in each state (ex. 0 stores, 1-5 stores, 6-10 stores, 10+ stores). Both shapefiles contain a STCODE field with the two-letter abbreviation for the state (ex. CA, FL, TX, MN, etc.)

I tried using the Field Calculator in the "States" layer to look in the "Widget_stores" layer and count the number of points (stores) located in each state either by geometry or by STCODE and assign that number to a new integer field NUMSTORES in the "States" layer so I can classify each state for the symbology. I constructed an expression using the "aggregate" function because the documentation says it returns an aggregate value from another layer, however the result was not what I expected - for each of the 50 states it returned the total number of stores. My expression must be missing a filter or some other operation needed to parse state-by-state. Here's my expression:

aggregate('Widget_stores','count_distinct', "STCODE")

Looking for suggestions on how to construct the proper expression!

  • Yes the filter is the fourth argument, but unfortunately you cannot use your STCODE field in the States layer. For instance aggregate('Widget_stores', 'count', "STCODE", "STCODE"='CA') can work but aggregate('Widget_stores', 'count', "STCODE", "STCODE"="STCODE") fails. Please see referencing to features geometry in an expression for the answer provided by Germán Carrillo.
    – Kazuhito
    Commented May 3, 2018 at 5:40
  • Try the plugin refFunctions. It gives more functions to use in the field calculator. I think "intersecting_geom_count() will do what you want.
    – csk
    Commented May 3, 2018 at 16:05
  • Thank you "csk" - that function does exactly what I want to do! In the way of further clarification, the function apparently compares similarly named fields (ex. "STCODE") rather than looking at the geometry. Thanks also Kazuhito for the reply, and I will check out your link for further education. Commented May 3, 2018 at 19:24


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.