Get to know the QGIS expression

Some time ago, many articles in the album "QGIS Practices and Techniques" used QGIS expressions , but they were not analyzed in depth due to space limitations. In fact, expressions are extremely powerful and flexible functions, and are the basis for the realization of many advanced functions of QGIS. This article attempts to introduce to you the basic concepts, application scenarios and usage methods of QGIS expressions as a whole, and subsequent articles will further elaborate on the many uses of expressions in depth.

01 What is an expression

An expression is a meaningful formula that connects the same type of data (such as constants, variables, functions, etc.) with arithmetic symbols according to certain rules.

Different from regular expressions, the expressions in QGIS are constructed on the basis of spatial data (fields, variables) and functions (preset functions, custom functions), and are used to manipulate geometric figures and attribute data, map symbolization, and print layout The output provides a powerful tool.

Many people are wondering which programming language the expression in QGIS is. In fact, it is a SQL-like language that supports a subset of SQL syntax. From a less rigorous point of view, expressions can be regarded as a simple sentence Program statement. Therefore, to understand and use expressions in depth, you need a little SQL language foundation and programming thinking.

02 Typical application scenarios of expressions

In QGIS, expressions are widely used to an amazing degree. Expressions can be seen in most of the cool rendering effects, advanced queries, and tedious and complex data updates.

  • Create or update attribute fields

In [Field Calculator], expressions can create fields based on existing spatial graphic features and attribute data, or update existing attribute fields as required, such as generating x and y coordinates based on the center point of a geometric figure, using population The number is divided by the area to calculate the population density field, etc.
Insert picture description here

  • Feature query and selection

The query and selection of elements are the basic operations of spatial data processing. Expressions are the best tool to filter data. For example, to find cities with a scale greater than 200 from cities across the country, you only need to establish the condition "city scale greater than 200", and all those that meet the conditions The elements can be extracted.
Insert picture description here

  • Symbolized data definition overload

In the process of map symbolization, various attributes of the symbol need to be set, such as the size and color of the point. These symbol attributes can be set by entering conventional numerical values ​​and color values, or their values ​​can be defined by expressions. The map rendering engine calculates the value of the expression in real time and assigns it to the corresponding symbol attribute. That is, the symbol attribute ignores the value given in the input box and takes the value from the expression calculation result. This process is called symbolic data definition re- Load. For example, the result of the expression in the following figure is: to determine whether the size of the city is greater than or equal to 200, if it is, the symbol size is set to 8, otherwise the symbol size is set to 2.
Insert picture description here

  • Print layout application

Expressions play an important role in making atlases. Usually the atlas will define labels based on the current map content, such as map name, mapping date, etc. Compared with manually inputting label content, using expressions can reduce a lot of manual labor.

Insert picture description here

03 Expression Constructor

The expression string constructor dialog box is the main interface for constructing expressions. QGIS provides multiple ways to call up the expression constructor:

1. Click the Insert picture description herebutton in QGIS .

2. Click the [ Use expression to select elements] button in the [Attribute] toolbar .

3. When editing attribute data, use Insert picture description here[Field Calculator].

4. When setting the symbolic style, label style, and layout elements, use Insert picture description here[override by data definition].

5. When using the [Geometric Generator] to render the layer.

No matter which context the expression is used in QGIS, the interface of the expression string constructor is roughly the same, as shown below:

Insert picture description here

The expression string constructor interface consists of three parts: the code input area on the left, the function and variable selection area in the middle, the help panel on the right, and the field value preview area.

The code input area is a text box where you can enter the expression code, or you can copy and paste the constructed expression into the code input area for execution. Below the code input area, there is a preview of the expression result. If there is no problem with the syntax and semantics, the expression calculation result will be displayed; if there is an error, a brief error description and a link to the detailed error information will be provided. Operator buttons are provided above the code input area. You can quickly enter operators when constructing expressions. The effect is the same as that of entering operators from the keyboard. You can also select the desired operation from the operator categories in the function and variable selection area. symbol.

Insert picture description here

The function and variable selection area is grouped to list functions and variables in a tree structure. QGIS divides functions and variables into about 20 categories, including variables, operators, maps, map layers, records and attributes, time and date, mathematics, arrays, conditions, etc. Due to the huge content of functions and variables and numerous entries, a search box is provided above the selection area for quick search by entering the name of the function or variable. Double-click a function or variable to add it to the code input area.
Insert picture description here

The help panel area changes with the selection of functions and variables. For functions, the help panel displays the description, parameters and examples of the function. If a variable is selected, the help panel will display the variable description and current value. If you select an attribute field, you can take out the first 10 values ​​of the field or take out all possible values ​​of the field and display them in the field value preview area. When constructing an expression, listing the possible values ​​of a field can facilitate the construction of the expression.

Insert picture description here

04 The composition of expressions

  • constant

Constants include three aspects: numeric constants, string constants, and attribute field references.

Numerical: Including integer values ​​and floating-point numeric constants with decimals, such as 123, 3.14.

String constant: The value is a string enclosed in single quotes, such as'one-way road'. Note that if the string constant contains a single quotation mark itself, it is represented by two consecutive single quotation marks, such as'this''s', and the calculation result is a string: this's.

Attribute field reference: The quoted attribute field is expressed by enclosing the field name in double quotation marks, such as "name". When the expression is calculated, the referenced attribute field is replaced with the actual field value.

  • variable

Variables in QGIS are used to store variable content in programs, items, layers or print layouts, such as the language settings of QGIS, current version, storage location of project files, current scale of the map, and the name of the print layout.

Variables follow the hierarchical structure, from top to bottom: global variables, project variables, layer variables, print layout variables, etc. From the function and variable selection area of ​​the expression string constructor, you can find the variable branch, which contains all the variable sets that can be used in the current context.

In the expression, the variable is represented by " @+variable name ".

  • function

Built-in functions in QGIS include aggregation, array, color, condition, conversion, date and time, aggregation, file and path, fuzzy matching, general, geometric graphics, print layout, map layer, map, math, processing, raster, record Groups with attributes, strings, etc. The number of functions included in each group is as follows:

Insert picture description here

05 Examples of expressions

1.

concat(to_string(@grid_number), '°    ')

This expression comes from "QGIS 3.10 Mapping Hand-in-hand Tutorial" , which constructs a suitable representation for the grid line label, that is, add'°' after the grid degree. Among them, concat is a string merging function, which merges two strings into one. to_string is a conversion function, @grid_number is a variable, which represents the current grid annotation value. Therefore, the meaning of the entire expression is: take out the current grid annotation value, convert it to a string, and merge with'°' to form a new grid annotation label.

2.

"primary_fuel" IN ('Biomass', 'Geothermal', 'Hydro', 'Solar', 'Wind', 'Storage', 'Wave and Tidal')

This expression comes from "QGIS 3.10 Vector Style Settings" , which is used to filter the elements to be rendered during rule-based symbol rendering. Among them, "primary_fuel" is enclosed in double quotation marks to indicate the field primary_fuel. IN is an operator, meaning that it returns 1 if it is in the value list. The following brackets are string constants. The meaning of the entire expression is: Find one of the values ​​in the attribute table field primary_fuel ('Biomass','Geothermal','Hydro','Solar','Wind','Storage','Wave and Tidal') The elements are displayed according to the set style.

3.

CASE
WHEN "Crime type" LIKE 'Violence%' THEN 10
WHEN "Crime type" LIKE 'Criminal%' THEN 5
ELSE 1
END

This expression comes from "QGIS 3.10 Making Heat Map" , which is used to create the violence degree weight field of the crime location layer. This expression uses the CASE WHEN… THEN… ELSE… END conditional function for multi-condition judgment, "Crime type" is the crime type field, and LIKE is the operator, which means that if the first parameter matches the provided pattern, it returns 1. The whole expression means: if the crime type ("Crime type") starts with Violence (violence), assign a weight of 10 to the crime event; if the crime type ("Crime type") starts with Criminal (criminal crime), then Assign a weight of 5 to the crime; in other cases, the weight is 1.

This article provides a preliminary introduction to QGIS expressions in terms of definition, application scenarios, expression builders, and expression composition. We will do in-depth analysis and sharing on this basis. If you are interested in the in-depth use of expressions, think To appreciate the powerful and flexible functions of expressions, stay tuned to the expression series articles.


Wu Jianling

July 24, 2020


Copyright Notice


This article welcomes reprinting, please indicate the source when reprinting.


Insert picture description here

Guess you like

Origin blog.csdn.net/QGISClass/article/details/107575534