如何将ggplot2图例中的指定部分文字设置为粗体?
解决ggplot2图例标签指定部分加粗的问题
要实现图例中指定文本加粗,核心是生成plotmath表达式向量而非纯字符串,让ggplot能够解析加粗语法。具体步骤如下:
生成带格式的表达式标签
在存储标签的df_text中,通过遍历heading_bold和normal_text列,用bquote()创建包含粗体格式的表达式,将需要加粗的标题部分用bold()包裹,再与普通文本拼接。在scale中指定表达式标签
在scale_fill_viridis_d()里,通过labels参数传入生成的表达式向量,同时保持limits与映射的merged_text值对应,确保标签匹配正确。
修改后的完整代码:
library(tidyverse) df <- data.frame(xx = c(0, 3), yy = c(0, 1)) df_text <- data.frame(start = c(0, 1, 2), end = c(1, 2, 3), heading_bold = c("title 1", "title 2", "title 3"), normal_text = c("i want this to be normal text title 1", "i want this to be normal text title 2", "i want this to be normal text title 3")) %>% mutate(merged_text = paste0(heading_bold, ": ", normal_text), # 生成包含粗体格式的表达式向量 label_expr = map2(heading_bold, normal_text, ~ bquote(bold(.(.x)) ~ ": " ~ .(.y)))) ggplot(df, aes(x = xx, y = yy)) + geom_rect(data = df_text, aes(xmin = start, xmax = end, fill = merged_text, ymin = 0, ymax = 1), inherit.aes = FALSE) + scale_fill_viridis_d(option = "A", name = "Legend", limits = df_text$merged_text, direction = -1, # 传入表达式作为图例标签 labels = df_text$label_expr)
关键说明
bquote(bold(.(.x)) ~ ": " ~ .(.y)):bquote()用于创建可插入变量的表达式,.()用来提取变量值,~是plotmath语法中的空格连接符,确保文本正确拼接。map2():遍历heading_bold和normal_text的每一组对应值,生成独立的表达式,最终得到一个表达式向量供ggplot解析。
内容的提问来源于stack exchange,提问作者user63230
相关产品推荐
相关产品推荐

