Related Plugins and Tags

QGIS Planet

Creating circular insets and other fun QGIS layout tricks

Thanks to the recent popularity of the “30 Day Map Challenge“, the month of November has become synonymous with beautiful maps and cartography. During this November we’ll be sharing a bunch of tips and tricks which utilise some advanced QGIS functionality to help create beautiful maps.

One technique which can dramatically improve the appearance of maps is to swap out rectangular inset maps for more organic shapes, such as circles or ovals.

Back in 2020, we had the opportunity to add support for directly creating circular insets in QGIS Print Layouts (thanks to sponsorship from the City of Canning, Australia!). While this functionality makes it easy to create non-rectangular inset maps the steps, many QGIS users may not be aware that this is possible, so we wanted to highlight this functionality for our first 30 Day Map Challenge post.

Let’s kick things off with an example map. We’ve shown below an extract from the 2032 Brisbane Olympic Bid that some of the North Road team helped create (on behalf of SMEC for EKS). This map is designed to highlight potential venues around South East Queensland and the travel options between these regions:

Venue Masterplan Brisbane 2032 Olympics
Venue Masterplan for 2032 Olympic Games, IOC Feasibility Assessment – Olympic Games, Brisbane February 2021

Circles featured heavily in previous Olympic bid maps (such as Budapest) where we took our inspiration from. This may, or may not, play a part in using the language of the target map audience – think Olympic rings!

Budapest Olympics 2024 MasterplanBudapest Olympics 2024 Masterplan

 

Step by Step Guide to Creating a Circle Inset

Firstly, prepare a print layout with both a main map and an inset map. Make sure that your inset map is large enough to cover your circular shape:

From the Print Layout toolbar, click on the Add Shape button and then select Add Ellipse:

Draw the ellipse over the middle of your inset map (hint: holding down Shift while drawing the ellipse will force it to a circular shape!). If you didn’t manage to create an exact circle then you can manually specify the width and height in the shape item’s properties. For this one, we went with a 50mm x 50mm circle:

Next, select the Inset Map item and in its Item Properties click on the Clipping Settings button:

In the Clipping Settings, scroll down to the second section and tick the Clip to Item box and select your Ellipse item from the list. (If you have labels shown in your inset map you may also want to check the “force labels inside clipping shape” option to force these labels inside the circle. If you don’t check this option then labels will be allowed to overflow outside of the circle shape.)

Your inset map will now be bound to the ellipse!

Here’s a bit more magic you could add to this map – in the Main Map’s properties, click on Overviews and set create one for the Inset map – it will nicely show the visible circular area and not the rectangle!

Bonus Points: Circular Title Text!

For advanced users, we’ve another fun tip…and when we say fun, we mean ‘let’s play with radians’! Here we’re going to create some title text and a wedged background which curves around the outside of our circular inset. This takes some fiddly playing around, but the end result can be visually striking! Here we’re going to push the QGIS print layout “HTML” item to create some advanced graphics, so some HTML and CSS coding experience is advantageous. (An alternative approach would be to use a vector illustration application like Inkscape, and add your title and circular background as an SVG item in the print layout).

We’ll start by creating some curved circular text:

First, add a “HTML frame” to your print layout:

HTML frames allow placement of dynamic content in your layouts, which can use HTML, CSS and JavaScript to create graphical components.

In the HTML item’s “source” box, add the following code:

<svg height="300" width="350">
        <defs>
            <clipPath id="circleView">
                <circle id="curve" cx="183" cy="156" r="25" fill="transparent" />
            </clipPath>
        </defs>
        <path id="forText" d="M 28,150, C 25,50, 180,-32,290,130" stroke="" fill="none"/>
            <text x="0" y="35" width="100">
                <textpath xlink:href="#forText">
                    <tspan font-weight="bold" fill="black">Place text here</tspan>
                </textpath>
            </text>
             <style>
    <![CDATA[
      text{
        dominant-baseline: hanging;
        font: 20px Arial;
      }
    ]]>
  </style>
</svg>

Now, let’s add in a background to bring more focus onto the title!

To add in the background, create another HTML item. We’ll again create the arc shape using an SVG element, so add the following code into the item’s source box:

<svg width="750" height="750" xmlns="http://www.w3.org/2000/svg">
  <path d="M 90 70
           A 56 56, 0, 0, 0, 133 140
           L 150 90 Z" fill="#414042" transform=" scale(2.1) rotate(68 150 150) " />/>
</svg>

(You can read more about SVG  curves and arcs paths over at MDN)

So there we go! These two techniques can help push your QGIS map creations further and make it easier to create beautiful cartography directly in QGIS itself. If you found these tips useful, keep an eye on this blog as we post more tips and tricks over the month of November. And don’t forget to follow the 30 day Map Challenge for a smorgasbord of absolutely stunning maps.

Exploring Reports in QGIS 3.0 – the Ultimate Guide!

In 2017 North Road ran a crowd funding campaign for extending QGIS’ Print Composer and adding a brand new reporting framework to QGIS. Thanks to numerous generous backers, this campaign was a success. With the final QGIS 3.0 release just around the corner, we thought this was a great time to explore the new reporting engine and what it offers.

We’ll start with a relatively simple project, containing some administrative boundaries, populated places, ports and airports.

Using the “Project” – “New Report” command, we then create a new blank report. Initially, there’s not much to look at – the dialog which is displayed looks much like the QGIS 3.0 Layout Designer, except for the new “Report Organizer” panel shown on the left:

QGIS reports can consist of multiple, nested sections. In our new blank report we initially have only the main report section. The only options present for this report section is to include an optional header and footer for the report. If we enable these, the header will be included as the very first page (or pages… individual parts of reports can be multi-page if desired) in the report, and the footer would be the last page. Let’s go ahead and enable the header, and hit the “Edit” button next to it:

A few things happen as a result. Firstly, an edit pencil is now shown next to the “Report” section in the Report Organizer, indicating that the report section is currently being edited in the designer. We also see a new blank page shown in the designer itself, with the small “Report Header” title. In QGIS reports, every component of the report is made up of individual layouts. They can be created and modified using the exact same tools as are available for standard print layouts – so you can use any desired combination of labels, pictures, maps, tables, etc. Let’s add some items to our report header to demonstrate:

We’ll also create a simple footer for the report, by checking the “Include report footer” option and hitting “Edit“.

Before proceeding further, let’s export this report and see what we get. Exporting is done from the Report menu – in this case we select “Export Report as PDF” to render the whole report to a PDF file. Here’s the not-very-impressive result – a two page PDF consisting of our header and footer:

Let’s make things more interesting. By hitting the green “+” button in the Report Organizer, we’re given a choice of new sections to add to our report.

Currently there’s two options – a “Single section” and a “Field group“. Expect this list to grow in future QGIS releases, but for now we’ll add a Field Group to our report. At its most basic level, you can think of a Field Group as the equivalent of a print atlas. You select a layer to iterate over, and the report will insert a section for each feature found. Selecting the new Field Group section reveals a number of new related settings:

In this case we’ve setup our Field Group so that we iterate over all the states from the “Admin Level 1” layer, using the values from the “adm1name” field. The same options for header and footer are present, together with a new option to include a “body” for this section. We’ll do that, and edit the body:

We’ve setup this body with a map (set to follow the current report feature – just like how a map item in an atlas can follow the current atlas feature), and a label showing the state’s name. If we went ahead and exported our report now, we’d get something like this:

First, the report header, than a page for each state, and finally the report footer. So more or less an atlas, but with a header and footer page. Let’s make things more interesting by adding a subsection to our state group. We do this by first selecting the state field group in the organizer, then hitting the + button and adding a new Field Group:

When a field group is iterating over its features, it will automatically filter these features to match the feature attributes from its parent groups. In this case, the subsection we added will iterate over a “Populated Places” layer, including a body section for each place encountered. The magic here is that the Populated Places layer has an attribute named “adm1name“, tagging each place with the state it’s contained within (if you’re lucky your data will already be structured like this – if not, run the Processing “Join by Location” algorithm and create your own field). When we export this report, QGIS will grab the first state from the Admin Level 1 layer, and then iterate over all the Populated Places with a matching “adm1name” value. Here’s what we get:

(Here we created a basic body for the Populated Places group, including a map of the place and a table of some place attributes). So our report is now a report header, a page for each state followed by a page for every populated place within that state, and finally the report footer. If we were to add a header for the Populated Places group, it would be included just before listing the populated places for each state:

Similarly, a footer for the Populated Places group would be inserted after the final place for each state is included.

In addition to nested subsections, subsections in a report can also be included consecutively. If we add a second subsection to the Admin Level 1 group for Airports, then our report will first list ALL the populated places for each state, followed by all the airports within that state, before proceeding to the next state. In this case our report would be structured like this:

(The key point here is that our Airports group is a subsection of the Admin Level 1 group – not the Populated Places group). Here’s what our report could look like now:

Combining nested and consecutive sections, together with section headers and footers allows for tons of flexibility. For instance, in the below report we add another field group as a child of the main report for the Ports layer. Now, after listing the states together with their populated places and airports, we’ll get a summary list of all the ports in the region:

This results in the last part of our report exporting as:

As you can start to imagine, reports in QGIS are extremely powerful and flexible! We’re extremely thankful for all the backers of our crowd funding campaign, without whom this work would not have been possible.

Stay tuned for more reporting and layouts work we have planned for QGIS 3.2!

 

QGIS layouts rewrite – progress report #1

Following our recent successful QGIS Layout and Reporting Engine crowdfunding campaign, we’ve been hard at working ripping up the internals of the QGIS 2.x print composer and rebuilding a brand new, shiny QGIS layouts engine. This is exciting work – it’s very satisfying to be able to cleanup a lot of the old composer code in QGIS and take opportunities along the way to fix long standing bugs and add new features.

While it’s not ready for daily use yet, there’s already been a lot of interesting changes which have landed in the layouts work as a result of this campaign. Let’s take a look at what’s been implemented so far…

  • We’ve added support for different measurements units all throughout layouts. While this means it’s now possible to set page sizes using centimeters, inches, pixels, points, etc, it goes much deeper than just that. In layouts, everything which has a size or position can take advantage of this unit support. So you can have page sizes in centimeters, but a map item with a size set in points, and positioned in millimeters! Having pixels as a unit type makes creation of screen-based layouts much easier – even right down to pixel perfect positioning and sizing of items…
  • Page handling has been totally reworked. Instead of the single “number of pages” control available in QGIS 2.x, layouts have complete flexibility in page setup. It’s now possible to have a layout with mixed page sizes and orientations (including data defined page size for different pages in the layout!). 
  • A revised status bar, with improved layout interaction widgets. We’ve also taken the opportunity to add some new features like a zoom level slider and option to zoom to layout width:
  • Layout interaction tools (such as pan/zoom/insert item/etc) have been reworked. There’s now a much more flexible framework for creation of layout tools (based off the main QGIS map canvas approach), which even allows for plugins to implement their own layout interaction tools! As part of this we’ve addressed a long standing annoyance which meant that creating new items always drew the “preview” shape of the new item as a rectangle – even for non-rectangular items. Now you get a real shape showing exactly how the created item will be sized and positioned:
  • On the topic of plugins – the layout branch has full support for plugin-provided item types. This means that QGIS plugins can create new classes of items which can be added to a layout. This opens the door for plugins allowing charts and visualisations which take advantage of all the mature Python and JS charting libraries! This is a really exciting change – in 2.x there was no way for plugins to extend or interact with composer, so we’re really keen to see where the community takes this when 3.0 is released.
  • We’ve ported another feature commonly found in illustration/DTP applications. Now, when you’re creating a new item and just click in your layout (instead of click-and-drag), you get a handy dialog allowing you to specify the exact position and dimensions for the created item. You can again see in this dialog how layouts have full support for units for both the position and size:
  • Another oft-requested feature which we’ve finally been able to add (thanks to the refactored and cleaned code) is a context menu for layouts! It’s currently quite empty, but will be expanded as this work progresses…
  • Snapping to guides and grids has been reworked. We’ve added a new snapping marker to show exactly were items will be snapped to:
  • Snapping to guides now occurs when creating new layout items (this didn’t happen in Composer in 2.x – only snapping to grids occurred when drawing new items).
  • The snapped cursor position is shown in status bar whenever a snapped point will be used, instead of the unsnapped position.
  • Unlike in Composers in QGIS 2.x, Layouts in 3.0 adopt the standard UX of dragging out rulers to create guide lines (instead of clicking on a ruler position to create a new guide). Creation of a horizontal guide is now done by grabbing the top ruler and dragging it down, and a vertical guide is created by grabbing the left ruler and dragging it out to the layout.
  • Better feedback is given in the ruler when a guide can be dragged. We now show guide positions in the rulers, and give an indication (via mouse cursor change) when these guides can be repositioned by click-and-drag.
  • Another very exciting change is the addition of a new “Guide Manager”. The guide manager allows numeric modification of existing guides and creation of new guides. Finally it’s possible to position guides at exact locations! Again, you can see the full support for layout units in place here – guides can be positioned using any available unit.
  • There’s also a handy new shortcut in the Guide Manager to allow applying the guides from the current page to all other pages in your layout.
  • We’ve refined the snapping logic. In Composer in QGIS 2.x,  grids would always take precedence whenever both a grid and guide were within tolerance of a point. Now, guides will always take precedence – since they have been manually set by users we make the assumption that they have been explicitly placed at highly desirable snapping locations, and should be selected over the general background grid. Additionally, grid snapping was previously only done if BOTH the x and y of the point could be snapped to the grid. We now snap to the nearest grid line for x/y separately. This means if a point is close to a vertical grid line but not a horizontal one it will still snap to that nearby vertical grid line.
  • Lastly, we’ve added a handy context menu to the rulers:

This is just a taster of the great new functionality coming in QGIS 3.0. This is all a direct result of the forward-thinking investments and generosity of the backers in our QGIS Layout and Reporting Engine crowdfunding campaign. Without their contributions, none of this would be possible – so our thanks go out to those organisations and individuals once again!

Stay tuned for more updates as the work continues…

 

 

QGIS Layout and Reporting Engine Campaign – a success!

Thanks to the tireless efforts and incredible generosity of the QGIS user community, our crowdfunded QGIS Layout and Reporting Engine campaign was a tremendous success! We’ve reached the funding goal for this project, and as a result QGIS 3.0 will include a more powerful print composer with a reworked code base. You can read more about what we have planned at the campaign page.

We’d like to take this opportunity to extend our heartfelt thanks to all the backers who have pledged to support this project:

We’ve also received numerous anonymous contributions in addition to these – please know that the QGIS community extends their gratitude for your contributions too! This campaign was also successful thanks to The Agency for Data Supply and Efficiency, Denmark, who stepped up and have funded an initial component of this project directly.

We’d also like to thank every member of the QGIS community who assisted with promoting this campaign and bringing it to the attention of these backers. Without your efforts we would not have been able to reach these backers and the campaign would not have been successful.

We’ll be posting more updates as this work progresses. Stay tuned…

 

QGIS Composer Rewrite and Layout Engine crowdfund launched!

At North Road we believe that crowdfunding is a sustainable way to maintain and enhance open source software, like the QGIS open source GIS package. We’ve run a number of successful crowdfunding campaigns in the past, including support in QGIS for live layer effects, a point cluster renderer, and a unique value renderer for raster layers.

Now, we’re proud to announce our latest crowd funding endeavour, and our biggest to date, the QGIS Layout and Reporting Engine Campaign.

This campaign covers stage 1 of a large, ongoing project to modernise and expand on QGIS’ print composer and layout facilities. Over time QGIS’ composer functionality has grown extensively and now is capable of creating flexible, high quality cartographic outputs. However, we’ve now hit a limit where the current code architecture is prohibiting further improvements and important fixes. In order to add a reporting framework to QGIS, it is necessary for us to refactor and improve large sections of the composer code.

If this campaign is successful, we’ll be adding flexible report generation features to QGIS and cleaning up all the existing composer code. As part of these clean up, we’ll be taking the opportunity to tackle a number of current limitations which cannot be addressed in the current composition code:

  • Layouts will become unit aware, allowing for item placement and properties using millimetres, inches, pixels, centimetres, points, etc.
  • Layouts will have the ability to include mixed page sizes and orientations.
  • Plugins will be able to create custom composer item types (eg allow utilisation of 3rd party graphing and visualisation libraries!).
  • Individual layout items can be rasterised without affecting the rest of the layout. For instance, a map which requires rasterisation due to its use of blend modes will not require all other layout items (such as headings, legends, etc) to be rasterised. This will greatly benefit PDF outputs for complex map layouts.
  • The code refresh will allow more extensive use of data defined layout item properties.
  • A render caching system will be implemented for items, speeding up use of the layout designer and also paving the way for use of live paint effects on layout items (eg dynamic drop shadows).

Full details on what we have planned are available here: QGIS Layout and Reporting Engine Campaign.

To make it possible we need 30,000€ pledged before 31 May 2017. You can help make this a reality by supporting the campaign or by sharing the campaign page and increasing exposure to the campaign. Updates to follow!

Small multiples for OD flow maps using virtual layers

In my previous posts, I discussed classic flow maps that use arrows of different width to encode flows between regions. This post presents an alternative take on visualizing flows, without any arrows. This style is inspired by Go with the Flow by Robert Radburn and Visualisation of origins, destinations and flows with OD maps by J. Wood et al.

The starting point of this visualization is a classic OD matrix.

migration_raw_data

For my previous flow maps, I already converted this data into a more GIS-friendly format: a Geopackage with lines and information about the origin, destination and strength of the flow:

migration_attribute_table

In addition, I grabbed state polygons from Natural Earth Data.

At this point, we have 72 flow features and 9 state polygon features. An ordinary join in the layer properties won’t do the trick. We’d still be stuck with only 9 polygons.

Virtual layers to the rescue!

The QGIS virtual layers feature (Layer menu | Add Layer | Add/Edit Virtual Layer) provides database capabilities without us having to actually set up a database … *win!*

Using a classic SQL query, we can join state polygons and migration flows into a new virtual layer:

virtual_layer

The resulting virtual layer contains 72 polygon features. There are 8 copies of each state.

Now that the data is ready, we can start designing the visualization in the Print Composer.

This is probably the most manual step in this whole process: We need 9 map items, one for each mini map in the small multiples visualization. Create one and configure it to your liking, then copy and paste to create 8 more copies.

I’ve decided to arrange the map items in a way that resembles the actual geographic location of the state that is represented by the respective map, from the state of Vorarlberg (a proud QGIS sponsor by the way) in the south-west to Lower Austria in the north-east.

To configure which map item will represent the flows from which origin state, we set the map item ID to the corresponding state ID. As you can see, the map items are numbered from 1 to 9:

small_multiples_print_composer_init

Once all map items are set up, we can use the map item IDs to filter the features in each map. This can be implemented using a rule based renderer:

small_multiples_style_rules

The first rule will ensure that the each map only shows flows originating from a specific state and the second rule will select the state itself.

We configure the symbol of the first rule to visualize the flow strength. The color represents the number number of people moving to the respective district. I’ve decided to use a smooth gradient instead of predefined classes for the polygon fill colors. The following expression maps the feature’s weight value to a shade on the Viridis color ramp:

ramp_color( 'Viridis',
  scale_linear("weight",0,2000,0,1)
)

You can use any color ramp you like. If you want to use the Viridis color ramp, save the following code into an .xml file and import it using the Style Manager. (This color ramp has been provided by Richard Styron on rocksandwater.net.)

<!DOCTYPE qgis_style>
<qgis_style version="0">
  <symbols/>
    <colorramp type="gradient" name="Viridis">
      <prop k="color1" v="68,1,84,255"/>
      <prop k="color2" v="253,231,36,255"/>
      <prop k="stops" v="0.04;71,15,98,255:0.08;72,29,111,255:0.12;71,42,121,255:0.16;69,54,129,255:0.20;65,66,134,255:0.23;60,77,138,255:0.27;55,88,140,255:0.31;50,98,141,255:0.35;46,108,142,255:0.39;42,118,142,255:0.43;38,127,142,255:0.47;35,137,141,255:0.51;31,146,140,255:0.55;30,155,137,255:0.59;32,165,133,255:0.62;40,174,127,255:0.66;53,183,120,255:0.70;69,191,111,255:0.74;89,199,100,255:0.78;112,206,86,255:0.82;136,213,71,255:0.86;162,218,55,255:0.90;189,222,38,255:0.94;215,226,25,255:0.98;241,229,28,255"/>
    </colorramp>
  </colorramps>
</qgis_style>

If we go back to the Print Composer and update the map item previews, we see it all come together:

small_multiples_print_composer

Finally, we set title, legend, explanatory texts, and background color:

migration

I think it is amazing that we are able to design a visualization like this without having to create any intermediate files or having to write custom code. Whenever a value is edited in the original migration dataset, the change is immediately reflected in the small multiples.


How to use Print Composer templates

In the previous post, Mickael shared a great map design. The download includes a print composer template, that you can use to recreate the design in a few simple steps:

1. Create a new composition based on a template

Open the Composer manager and configure it to use a specific template. Then you can select the .qpt template file and press the Add button to create a new composition based on the template.

2. Update image item paths

If the template uses images, the paths to the images most likely need to be fixed since the .qpt file stores absolute file paths instead of relative ones.

update_image_paths

With these steps, you’re now ready to use the design for your own maps. Happy QGISing!


Material design map tutorial for QGIS Composer

This is a guest post by Mickael HOARAU @Oneil974

For those wishing to get a stylized map on QGIS composer, I’ve been working on a tutorial to share with you a project I’m working on. Fan of web design and GIS user since few years, I wanted to merge Material Design Style with Map composer. Here is a tutorial to show you how to make simply a Material Design Map style on QGIS.

Click to view slideshow.

You can download tutorial here:

Tutorial Material Design Map

And sources here:

Sources Material Design Map

An Atlas Powered version is coming soon!


Exploring variables in QGIS 2.12, part 1

It’s been quite some time since I last had a chance to blog and a lot has happened since then. Not least of which is that QGIS 2.12 has now been released with a ton of new features that I’ve neglected to write about! To try and get things moving along here again I’m planning on writing a short series exploring how variables work in QGIS 2.12 and the exciting possibilities they unlock. First, let’s look into how variables can be used with QGIS map composer…

So, let’s get started! A new concept introduced in QGIS 2.12 is the ability to set custom variables for use in QGIS’ expression engine. The easiest way to do this is through the “Project Properties” dialog, under the “Variables” section:

Default project variables
Default project variables

You’ll see in the screenshot above that a blank project includes a number of read-only preset variables, such as @project_path and @project_title. (All variables in QGIS are prefixed with an @ character to differentiate them from fields or functions). You can add your own variables to this list by clicking the + button, as shown below:

Adding new variables to a project
Adding new variables to a project

Here I’ve added some new variables, @project_version and @author. Now, any of these variables can be used anywhere that you can use expressions in QGIS, including the field calculator, data defined symbology, labelling, map composer text, etc. So, you could make a map composer template with a label that includes the @author, @project_version and @project_path variables:

Variables in a composer label
Variables in a composer label

Sure, you *could* also manually enter all these details directly into the label for the same result. But what happens when you have multiple composers in your project, and need to update the version number in all of them? Or you move your project to a new folder and need to make sure the path is updated accordingly? Manually updating multiple composers is a pain – make QGIS do the work for you and instead use variables! This would especially be helpful if you’re saving map composer templates for use across multiple projects or users. Using variables will ensure that the template is automatically updated with the right details for the current project.

Another neat thing about QGIS variables is that they can be inherited and overridden, just like CSS rules. Opening the options dialog will also show a Variables group for setting “Global” variables. These variables are always available for your QGIS installation, regardless of what project you’re working on at the time. If your workplace tends to reorganise a lot and constantly shuffle your department around, you could add a global variable for @work_department, so that changing the global variable value in one place will automatically filter through to any existing and future projects you have.

Global variables
Global variables

And like I mentioned earlier, these variables are inherited through various “contexts” within QGIS. If I reopen the Project Properties dialog, you’ll see that a project has access to all the global variables plus the variables set within that specific project. In addition, by adding a variable with the same name to the Project variables the value of the Global variable will be overridden:

Overridden variables
Overridden variables

There’s also a variable editor within each individual composer’s properties tab, so variables can also be set and overridden on a composer-by-composer basis within a project. It’s a really flexible and powerful approach which both simplifies workflows and also opens up lots of new possibilities.

Stay tuned for more on this topic – this topic has only just scratched the surface of how expression variables have changed QGIS! (You can also read part 2 and part 3)

Exploring variables in QGIS 2.12, part 1

It’s been quite some time since I last had a chance to blog and a lot has happened since then. Not least of which is that QGIS 2.12 has now been released with a ton of new features that I’ve neglected to write about! To try and get things moving along here again I’m planning on writing a short series exploring how variables work in QGIS 2.12 and the exciting possibilities they unlock. First, let’s look into how variables can be used with QGIS map composer…

So, let’s get started! A new concept introduced in QGIS 2.12 is the ability to set custom variables for use in QGIS’ expression engine. The easiest way to do this is through the “Project Properties” dialog, under the “Variables” section:

Default project variables

Default project variables

You’ll see in the screenshot above that a blank project includes a number of read-only preset variables, such as @project_path and @project_title. (All variables in QGIS are prefixed with an @ character to differentiate them from fields or functions). You can add your own variables to this list by clicking the + button, as shown below:

Adding new variables to a project

Adding new variables to a project

Here I’ve added some new variables, @project_version and @author. Now, any of these variables can be used anywhere that you can use expressions in QGIS, including the field calculator, data defined symbology, labelling, map composer text, etc. So, you could make a map composer template with a label that includes the @author, @project_version and @project_path variables:

Variables in a composer label

Variables in a composer label

Sure, you *could* also manually enter all these details directly into the label for the same result. But what happens when you have multiple composers in your project, and need to update the version number in all of them? Or you move your project to a new folder and need to make sure the path is updated accordingly? Manually updating multiple composers is a pain – make QGIS do the work for you and instead use variables! This would especially be helpful if you’re saving map composer templates for use across multiple projects or users. Using variables will ensure that the template is automatically updated with the right details for the current project.

Another neat thing about QGIS variables is that they can be inherited and overridden, just like CSS rules. Opening the options dialog will also show a Variables group for setting “Global” variables. These variables are always available for your QGIS installation, regardless of what project you’re working on at the time. If your workplace tends to reorganise a lot and constantly shuffle your department around, you could add a global variable for @work_department, so that changing the global variable value in one place will automatically filter through to any existing and future projects you have.

Global variables

Global variables

And like I mentioned earlier, these variables are inherited through various “contexts” within QGIS. If I reopen the Project Properties dialog, you’ll see that a project has access to all the global variables plus the variables set within that specific project. In addition, by adding a variable with the same name to the Project variables the value of the Global variable will be overridden:

Overridden variables

Overridden variables

There’s also a variable editor within each individual composer’s properties tab, so variables can also be set and overridden on a composer-by-composer basis within a project. It’s a really flexible and powerful approach which both simplifies workflows and also opens up lots of new possibilities.

Stay tuned for more on this topic – this topic has only just scratched the surface of how expression variables have changed QGIS! (You can also read part 2 and part 3)

Accessing composer item properties via custom expressions in QGIS

So here is a neat trick. Lets say you wanted to access the scale of a composer map to make it part of a label. The scale bar can already be set to numeric to show the number value but what if it needs to be part of an existing label with other text. Not to fear, expression functions are here.

  • Create a new composer. Add the map frame and a label.
  • Set the item ID of the map frame to something you can remember, lets just use themap
  • Select the label and add some text
  • Click Insert Expression

Now for the cool part

  • Select Function Editor
  • Click New File. Give the file a new name and hit save. I called it composer functions.

In the code editor paste this code:

from qgis.utils import iface
from qgis.core import *
from qgis.gui import *

@qgsfunction(args="auto", group='Composer')
def composeritemattr(composername, mapname, attrname, feature, parent):
    composers = iface.activeComposers()
    # Find the composer with the given name
    comp = [composer.composition() for composer in composers 
                if composer.composerWindow().windowTitle() == composername][0]
    # Find the item
    item = comp.getComposerItemById(mapname)
    # Get the attr by name and call 
    return getattr(item, attrname)()
  • Click Run Script

run

Now in your label use this text:

Scale: [% composeritemattr('Composer 1', 'themap', 'scale')%]

Update the Composer 1 to match your composer name, and the themap to match your item ID.

and like magic here is the scale from the map item in a label:

2015-05-21 22_00_09-Composer 1

Check the expression error section if the label doesn’t render

error


Filed under: Open Source, qgis Tagged: composer, python, qgis

Multiple format map series using QGIS 2.6 – Part 1

EN | PT

As always, the new QGIS version (QGIS 2.6 Brigthon) brings a vast new set of features that will allow the user to do more, better and faster than with the earlier version. One of this features is the ability to control some of the composer’s items properties with data (for instance, size and position). Something that will allow lots of new interesting usages. In the next posts, I propose to show how to create map series with multiple formats.

In this first post, the goal is that, keeping the page size, the map is created with the most suitable orientation (landscape or portrait) to fit the atlas feature. To exemplify, I will be using the Alaska’s sample dataset to create a map for each of Alaska’s regions.

I have started by creating the layout in one of the formats, putting the items in the desired positions.

mapa_base_atlas

To control the page orientation with the atlas feature, in the composition tab, I used the following expression in the orientation data defined properties:

CASE WHEN bounds_width( $atlasgeometry ) >=  bounds_height( $atlasgeometry ) THEN 'landscape' ELSE 'portrait' END

Using the atlas preview, I could verify that the page’s orientation changed according to the form of the atlas feature. However, the composition’s items did not follow this change and some got even outside the printing area

Screenshot from 2014-11-08 23:29:49

To control both size and position of the composition’s items I had in consideration the A4 page size (297 x 210 mm), the map margins ( 20 mm, 5 mm, 10 mm, 5 mm) and the item’s reference points.

For the map item, using the upper left corner as reference point, it was necessary to change it’s height and width. I knew that the item height was the subtraction of the top and bottom margins (30 mm) from the page height, therefore I used the following expression:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 297 ELSE 210 END) - 30

Likewise, the expression to use in the width was:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 210 ELSE 297 END) - 10

Screenshot from 2014-11-09 00:02:15

The rest of the items were always at a relative position of the page without the need to change their size and therefore only needed to control their position. For example, the title was centered at the page’s top, and therefore, using the top-center as reference point, all that was needed was the following expression for the X position:

Screenshot from 2014-11-09 00:13:17

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry)  THEN 297 ELSE 210 END)  / 2.0

Screenshot from 2014-11-09 00:30:57

On the other hand, the legend needed to change the position in both X and Y. Using the bottom-right-corner as reference point, the X position expression was:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 297 ELSE 210 END) - 7

And for the Y position:

(CASE WHEN  bounds_width(  $atlasgeometry ) >=  bounds_height( $atlasgeometry) THEN 210 ELSE 297 END) - 12

Screenshot from 2014-11-09 00:47:28

For the remaining items (North arrow, scalebar, and bottom left text), the expression were similar to the ones already mentioned, and, after setting them for each item, I got a layout that would adapt to both page orientation.

output_9

From that point, printing/exporting all (25) maps was one click away.

mosaico_regioes

In the next post of the series, I will try to explain how to create map series where it’s the size of the page that change to keep the scale’s value of the scale constant.

Exploring QGIS 2.6 – Item panel for map composer

In recent releases QGIS’ map composer has undergone some large usability improvements, such as the ability to select and interact with multiple items, and much improved navigation of compositions. Another massive usability improvement which is included in QGIS 2.6 is the new “Items” panel in the map composer. The panel shows a list of all items currently in the composition, and allows you to individually select, show or hide items, toggle their lock status, and rearrange them via drag and drop. You can also double click the item’s description to modify its ID, which makes managing items in the composition much easier.

QGIS composer’s new items panel

This change has been on my wish list for a long time. The best bit is that implementing the panel has allowed me to fix some of the composer’s other biggest usability issues. For instance, now locked items are no longer selectable in the main composer view. If you’ve ever tried to create fancy compositions with items which are stacked on top of other items, you’ll know that trying to interact with the lower items has been almost impossible in previous QGIS versions. Now, if you lock the higher stacked items you’ll be able to fully interact with all underlying items without the higher items getting in the way. Alternatively you could just temporarily hide them while you work with the lower items.

This feature brings us one more step closer to making QGIS’ map composer a powerful DTP tool in itself. If you’d like to help support further improvements like this in QGIS, please consider sponsoring my development work, or you can contact me directly for a quote on specific development.

And now… colour preview modes in QGIS’ map canvas

As a quick follow-up to my last post on colour preview modes for the print composer in QGIS 2.4, this feature has also been added to the main map canvas window! Now it’s even easier to adjust your symbol colours and immediately see how they’d appear under a range of different circumstances:

Colour previews modes for the map canvas

Colour previews modes for the map canvas

 

Colour blindness and grayscale previews in QGIS 2.4

Since QGIS 2.4 is nearing feature freeze it seems like a good time to start exploring some of the great new features in this release. So, let’s get started with my most recent addition to QGIS’ print composer… preview modes!

As every first year cartography text book will tell you, it’s important to know your target media and audience when creating a usable map. Some important considerations are whether or not your map will be photocopied or printed in black and white, and whether you need to consider colour blind map readers in your audience. In the past, designing maps with these considerations has been a time consuming, tedious process. You’d have to export your map, open it in another graphics editing program, apply some colour transform, work out what issues there are, flip back to QGIS, make your changes and repeat. If you’re working with a tight deadline it can be difficult to justify the time this all takes.

QGIS 2.4 will help to make this whole process a lot simpler. In the print composer there’s now an option to enable a number of different live “preview modes“. These include grayscale, monochrome, and two colour blindness simulations (Protanope and Deuteranope).

Composer preview modes in QGIS 2.4

Composer preview modes in QGIS 2.4

These preview modes are live, so you can continue to edit and tweak the colours in your composition while a preview mode is active! For a quick demonstration, let’s start with this creatively coloured thematic map:

bad_colored_map

While it might not be the most aesthetically pleasing map, at least the thematic colours can be easily matched to their corresponding values in the legend. Let’s see what would happen if we photocopied this map. This is as easy as activating the “Simulate photocopy (grayscale)” preview mode:

greyscalepreview

Hmm… not so usable now. The five thematic colours have been reduced to just three discernible colours. Oh well, at least we haven’t had to export our map to find this out, and it’s nice and easy to adjust the colours and composition to work for photocopies without having to leave QGIS to test the results!

Let’s see how this map would look to someone with colour blindness, by activating the “Simulate colour blindness (Protanope)” mode:

color_blindness

In this case, our map isn’t too bad. The different classes are still discernible and the map can be interpreted by someone with protanopia.

So there we have it – now it’s easy to determine how our map outputs will look under different circumstances and adjust them to suit! Composer preview modes will be a part of the upcoming 2.4 release of QGIS, which is due out at the end of June 2014.

Update:

This feature has also been added to the main map canvas.

Composition styling in QGIS 2.2

Here’s a quick run-down on some new feature in QGIS 2.2 which I never got around to writing about before the release. I feel like I’ve got to give these features their due publicity before moving on to all the exciting new stuff which is being added for 2.4. So, without further ado, let’s take a dive into print composer shape and page styling in QGIS 2.2…

Shape styling

It’s no secret that QGIS has pretty impressive capabilities when it comes to cartographic styling of polygon features. Everything from line and point pattern fills, SVG image fills, gradients and even buffered gradients (new in 2.4 — more on that in a later post) can be used to shade polygons. That’s all in addition to the whole range of line styles which can be used to outline the edges of polygons. In QGIS 2.2 all these fill effects are now available for styling shapes in the print composer. What exactly does this mean?

Well, now you can draw a frame onto your print layout and style it with a gradient fill…

Gradient shape fill in composer

…or a line pattern fill….

Line pattern fill in composer

…or some crazy combination of everything…

Advanced fill in composer

It’s totally up to you how far you take this! Here’s a nice example of a map created in QGIS 2.2’s print composer using these new styling options.

Page styling for compositions

Why is this cool? Well, for a start, if we take a quick look at the QGIS map showcase on Flickr very few of the maps shown there have a white background. In previous versions of QGIS achieving a non-white background would require drawing a giant coloured rectangle over your whole composition, banishing it to the back of the stack, and then continually being annoyed by it getting in the way while you tried to work on the rest of the composition. Now, just like the shape styling described above, you can style the page background using any of the available options in QGIS for polygon fills!

Creating a composition with a black page background

Creating a composition with a black page background

It doesn’t end there though. Since the page background can now be styled like this, it’s also possible to have transparent or semi-transparent page backgrounds. I’ll show the result opened here in GIMP so that you can see the full transparency effect over GIMP’s checkerboard background pattern:

A composition exported with a transparent background

A QGIS 2.2 composition exported with a transparent background

Using a transparent composition background like this also allows for transparency effects in map layers to show through – so, for instance, if your map layer is set to 50% transparent then the resultant export from the composer will also be 50% transparent.

And now for the final stinger…

Have I mentioned yet that you can also use data defined symbology for both shape and page styling? No? Well, this was actually my main motivator in adding styling support to these elements. For a long time I’ve been wanting to create atlases which vary the page background based on attributes in the atlas coverage layer. Think flip-book style maps, where the page border is colour-coded to highlight areas that need attention. For example, areas with high rates showing with red borders, average rates with yellow, and low rates with green borders. Using a combination of page and shape styling, data defined symbology, and QGIS’ atlas features, this is now possible!

…And that (belatedly) wraps up my exploration of new features in QGIS 2.2. Next up I’ll start showcasing all the sweet new features which have landed for 2.4…

Atlas previews in QGIS 2.2

QGIS 2.2 includes some great additions to the map composer’s “Atlas” feature. If you’re not familiar with atlas prints they are QGIS’ equivalent of ArcGIS’s “data driven pages”, or something like a map based version of Microsoft Word’s “mail merge”. In an atlas composition you can select one of your map layers to use as a “coverage layer“, and QGIS will automatically generate multiple pages from the composition with each page highlighting a different feature from this coverage layer.

Atlas Previews

Thanks to funding from SIGE, I’ve added some useful new features to QGIS’ atlas abilities for 2.2. The first of these is the ability to preview atlas compositions before printing them. In QGIS 2.0, atlas generation took a bit of guess work. You’d set up the parameters for the atlas, then export the whole atlas in one shot and just hope you’d got the settings right. If not, you’d have to tweak the settings and export the whole lot again to see the result. But not any more! Now, in QGIS 2.2, you can switch on a live atlas preview mode by clicking “Preview Atlas” in the new atlas preview toolbar:

The new atlas preview toolbar

The new atlas preview toolbar

The composer window will switch to showing you a preview of exactly how the atlas will look when exported. You can tweak the appearance of any layout item, adjust the atlas and map parameters, or experiment with the new options for atlas feature styling to see instantly what the final export will look like.

The composer window in atlas preview mode

The composer window in atlas preview mode (complete with gratuitous use of label rotation and rounded rectangles…) 

When this Atlas Preview mode is enabled, you navigate through all the features in the coverage layer by clicking any of the navigation buttons in the atlas preview toolbar:

Navigating the atlas preview

Navigating the atlas preview

While previewing you can export individual pages from the atlas. So, if just one or two pages in your atlas need to be individually tweaked you can do that as you step through the features. A neat thing with this is that you can make temporary tweaks to the extent and scale of the map items as you go, without affecting how the rest of the atlas maps look.

(Oh, by the way, I should mention that as an added bonus QGIS 2.2 lets you control more than one map with an atlas print!)

Selecting the current atlas feature

The second part of the work funded by SIGE was creation of shortcut actions for selecting the current atlas feature. If your atlas coverage layer has many records it may not be practical to step through the atlas previews one at a time until you find a specific feature. That’s where these new shortcut actions come in handy!

There’s a few ways of jumping directly to a specific atlas feature. The first is to open a browser window for your coverage layer, then right click a row and choose “Set as atlas feature for …“:

Setting the atlas feature from the browser window

Setting the atlas feature from the browser window

Selecting this menu item will cause the composer to immediately jump to the matching atlas row. Another way of selecting the current atlas feature is to use the “Set as atlas feature” map action. You activate this by first selecting your coverage layer in the layers panel, then clicking the “Run Feature Action” tool button and selecting “Set as atlas feature…“:

The set atlas feature map action

The set atlas feature map action

The mouse cursor will change to a cross-hair, and clicking any matching feature in the map window will cause the composer atlas preview to jump straight to that feature. Lastly, you can also activate the “Set as atlas feature” action directly from the identify results window.

That’s just a small taste of some of the new atlas creation features which will be available in QGIS 2.2, coming your way by the end of February 2014!

(One last note – as mentioned, this work was kindly sponsored by SIGE. If there’s a specific composer based feature or bug you’d like me to work on, I’m available for further sponsored work. Just contact me directly for details.)

QGIS – Two neat features in 2.2

Here’s a quick run-down on two nice new styling options which I’ve recently added to QGIS 2.2.

Map styling for compositions

This little feature was suggested by Mathieu Pellerin, who is always pushing the boundaries of QGIS’ cartographic tools and coming up with great ideas for new styling features (you can check out some of his work via Flickr). Mathieu’s idea was for a new ‘$map‘ variable for the expression builder. This variable holds the id of the map item which is drawing the map, and allows for some nice tweaking of maps in the composer.

The $map variable is most useful when you have more than one map in your composition. The example below shows $map being used to change the styling of a single layer from the main map to the smaller inset map:

Using $map to style two maps with different colours

Using $map to style a single layer in two maps with different colours

In this example the composition has two maps, the larger has an id of “main_map” and the smaller has “inset_map“. The boundary layer has been styled using the rule based renderer, with one rule for $map=’main_map’ and one for $map=’inset_map’, as shown below:

Rule based rendering using the $map variable

Rule based rendering using the $map variable

The end result is that the layer will be rendered using the two different styles depending on which composer map item it is being drawn into. This trick can also be used to tweak labelling rules between the maps. In the example above I’ve restricted the labelling to only show in the main map. This is achieved by setting an expression for the data defined “Show label” property. I’ve used the expression “$map=’main_map’” so that labels are only shown in the main map and not the smaller inset map.

Tweaking label settings using the $map variable

Tweaking label settings using the $map variable

This small addition to QGIS 2.2 allows for some rather powerful improvements to multi-map compositions!

Drawing polygon borders only inside the polygon

The second new feature I wanted to highlight is a new option for polygon outlines which causes the outline to be drawn only on the inside of a polygon feature. The usual behaviour is for outlines to be drawn directly over the centre of the feature boundary, so that half of the outline is drawn inside the feature and half on the outside.

Simple Line Fill before

This means that the outline in a simple line symbol layer overlaps into the neighbouring polygons, and the result is that outlines from these features blend together:

Shaded borders pre QGIS 2.2

Shaded borders pre QGIS 2.2 – see how the colours bleed into the neighbouring features and overlap

This looks like a big muddy mess. A feature I’ve wanted for a long time is the ability to restrict these outlines so that they are only drawn inside the feature. This effect is commonly seen in world atlases and National Geographic maps, where each neighbouring country is shaded with it’s own unique outline colour. Now it’s possible to do this in QGIS just by ticking a single box!

The new "Draw line only inside polygon" option

The new “Draw line only inside polygon” option

As you can see in the above image, the simple line outline style has a new checkbox, “Draw line only inside polygon“. Ticking this box will clip the outline so that only the portion of it which falls inside the feature is rendered. Here’s the result:

Shaded borders with "Draw line only inside polygon" checked

Shaded borders with “Draw line only inside polygon” checked

So much nicer then the earlier output – now none of the borders overlap into their neighbouring regions! Ok, so it is possible to achieve a similar result by creating a specially crafted layer consisting of negatively buffered polygons subtracted from the original polygons, but this takes a lot of fiddling around. It also has the major disadvantage in that the result is scale dependant, and zooming in or out of the map will alter the size of the polygon outlines. But using this wonderful new checkbox in QGIS, we get proper scale-independent borders, and zooming in or out of the map keeps a consistent border width!

Zooming in keeps a consistent border width...

Zooming in keeps a consistent border width…

So there we go – two small new features added in QGIS 2.2 which have huge potential for your cartographic outputs! As per usual, if you come up with some fancy way of utilising these, don’t forget to add your maps to the QGIS Showcase on Flickr.

Waiting for QGIS 2.2 – Composer Improvements (part 3)

Following on from parts 1 and 2, here’s some more composer changes which are coming in QGIS 2.2

  • Rotation support for all composer item types. Now anything you draw in a composer can be rotated, including scale bars, legends, attribute tables and html frames! Rotation of text labels has also been improved by making the border and background of labels respect the rotation of the label.
Every composer item can now be rotated...

Every composer item can now be rotated…

  • Resizing of rotated items has been improved. Now it’s possible to easily resize rotated items while keeping their correct shape. (There’s still one missing ingredient for complete support here – shear/perspective transforms. Unfortunately this will probably have to wait till 2.4).
Better resizing of rotated items

Better resizing of rotated items

  • Rulers can be shown or hidden in compositions
  • The ruler appearance has been tweaked, adding smaller divisions and better text placement
The ruler appearance has been tweaked

New tweaked appearance for rulers

  • A zoom to actual size button and short cut (Ctrl + 1) have been added
Zoom to 100%

New Zom to 100% button

  • Lastly, the status bar has a new zoom combo box, which shows the current zoom level and allows for quick zoom to several predefined levels. You can also enter an exact zoom level in the box for precise control.
New zoom levels combo box in the status bar

New zoom levels combo box in the status bar

As you can see, the print composer in QGIS 2.2 just keeps getting better! There’s a few other really exciting new additions which have landed recently too, but they deserve their own blog posts. Stay tuned…

Waiting for QGIS 2.2 – Composer Improvements (part 2)

Following on from Part 1, here’s some more recent usability improvements which have been made to QGIS’ map composer:

  • Multiple items can now be selected by drawing a box around them. Holding Shift while drawing a box adds to the current selection, holding Ctrl will subtract from the current selection. In addition, holding Alt while drawing the selection box changes from an “intersects” style selection mode to a “within” selection mode. This was my major frustration with the composer in earlier versions of QGIS, and combined with the earlier fixes for multi-item drag and resize it substantially improves the design workflow.
Selecting multiple items with a mouse drag

Selecting multiple items with a mouse drag

  • Grid lines are always drawn on top of compositions
  • There’s new menu options for showing the grid and snapping to grid, and for showing/snapping/smart guides. All these have convenient keyboard shortcuts so you can quickly switch on or off display of the guides and grid or temporarily switch on or off snapping while you work. There’s also a new menu item for clearing all guides from a composition.
Grid and guide controls in the view menu

Grid and guide controls in the view menu

  • The composer window now has a status bar which shows the exact cursor position and details about resizing/moving items
The new composer status bar

The new composer status bar

  • A new mouse-based zoom tool has been added to the composer, which allows you to click and drag to specify an area to zoom to. You can also switch to this new tool at any time by holding Ctrl and space. Holding Shift while using the zoom tool switches to zooming out.

That’s it for now, but there’s loads more to come for 2.2!

  • Page 1 of 2 ( 22 posts )
  • >>
  • composer

Back to Top

Sustaining Members