4

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 ) )%]"
0
4

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.