如何在tmap中使用变量时仅格式化标题文本的部分内容?
在tmap中格式化含变量的文本(如斜体物种名)
要实现将存储在变量中的文本设为斜体(比如图例标题里的物种学名),直接用expression()会显示变量名而非实际值,这时候可以用bquote()或substitute()来动态替换变量:
方法1:使用bquote()
bquote()允许你通过.语法插入变量的实际值,结合~添加空格,示例代码如下:
library(tmap) data("World") species <- "Falco peregrinus" tm_shape(World) + tm_polygons(col = "continent", title = bquote(Continents with ~italic(.(species)))) + tm_layout(legend.outside = TRUE)
这里.(species)会被替换为变量的实际值,~用来连接文本和斜体部分,保证排版有空格。
方法2:使用substitute()
substitute()可以替换表达式中的符号,通过list()指定替换规则:
library(tmap) data("World") species <- "Falco peregrinus" tm_shape(World) + tm_polygons(col = "continent", title = substitute(paste("Continents with ", italic(x)), list(x = species))) + tm_layout(legend.outside = TRUE)
paste()用来拼接文本,list(x = species)把表达式里的x替换为变量值。
这两种方法都能让图例标题正确显示“Continents with Falco peregrinus”(斜体的物种名),而非变量名。
内容的提问来源于stack exchange,提问作者Simeon
相关产品推荐
相关产品推荐

