TransWikia.com

Update a round numeric scale with atlas page - PyQGIS3

Geographic Information Systems Asked on June 1, 2021

I would like to add a rounded numeric scale to each map of my atlas, with a blank as thousands separator.

The code below allows to produce this kind of numeric scale but it’s not changing with the atlas page, because it takes the scale of the map defined by default into the map item.

numScaleLabel = math.trunc(round(map.scale(), 0)) # get the scale without decimal numbers
numLab = QgsLayoutItemLabel(layout) #define the scale as a label instead of a scalebar item
numLab.setText('1 : ' + str(f'{numScaleLabel:,}'.replace(",", " "))) # set text with thousands separator
layout.addLayoutItem(numLab) # add the numeric scale to the layout

enter image description here

I think that I need to use @map_scale in the text expression to update the scale for each page, but what I tried didn’t work. No error is returned, but the expression seems not valid because no text appears.

text = "[% '1 : ' + to_string(round(@map_scale,0))%]"
numLab.setText(text)
layout.addLayoutItem(numLab)

myAtlas.beginRender()
for numLab in range(myAtlas.count()):
    myAtlas.next()
    
myAtlas.endRender()

UPDATE

I first need to define an id for my map, then the following expression works great. Looks like the math.trunc() function is not required :

map.setId('map1') #id must have no space
text = "[%'1 : ' + to_string( round( map_get( item_variables('map1'), 'map_scale' ), 0 ) )%]"

One Answer

Use this expression for the label:

'1 : ' + to_string( round( map_get( item_variables('MyMap'), 'map_scale' ), 0 ) )

enter image description here

enter image description here

Correct answer by Kadir Şahbaz on June 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP