You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:52:10