tmap
tmap copied to clipboard
Mathematical expressions for text elements
I am trying to have mathematical expression in the panel labels. It was working with tmap version 3. I am using the following code:
library(tmap)
library(terra)
library(sf)
r <- rast(system.file("ex/elev.tif", package="terra"))
states <- st_read(system.file("ex/lux.shp", package="terra"))
# make some bbox magic
bbox_new <- st_bbox(r) # current bounding box
xrange <- bbox_new$xmax - bbox_new$xmin # range of x values
yrange <- bbox_new$ymax - bbox_new$ymin # range of y values
bbox_new[1] <- bbox_new[1] - (0.05 * xrange) # xmin - left
bbox_new[3] <- bbox_new[3] + (0.05 * xrange) # xmax - right
bbox_new[2] <- bbox_new[2] - (0.05 * yrange) # ymin - bottom
bbox_new[4] <- bbox_new[4] + (0.05 * yrange) # ymax - top
bbox_new <- bbox_new %>% # take the bounding box ...
st_as_sfc() # ... and make it a sf polygon
tm_shape(r, bbox = bbox_new) +
tm_raster(col.scale = tm_scale_continuous(
values = "viridis"), # color palette;
col.legend = tm_legend(title = "Legend", frame.lwd = 0,
position = c("LEFT", "BOTTOM"))) +
tm_shape(states) +
tm_borders() +
tm_layout(panel.labels = expression(bold("Elevation (No. m"^-2*")"))) #Fake unit just to show
which returns me
Error in bold("Elevation (No. m"^-2 * ")") : could not find function "bold"
How to have superscripts and subscripts in panel labels using tmap v.4?
Working now. Approach is to use a encoder and decoder. Will leave this issue open, because we need to make this work for other text components as well. Expressions are working for tm_title etc, but I think this new approach is easier.
Please test.