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

如何在R语言ggplot2图形的分组标签中添加下标

R语言ggplot分组标签下标设置方案

你当前通过scale_shape_manual设置分组标签,要实现下标效果,可通过表达式构造或文本解析两种方式修改labels参数,具体实现如下:

方法1:直接用expression构造标签向量

将需要设为下标的内容用[]包裹,字符串部分用单引号括住避免语法报错,修改point_4代码:

point_4 <- list(scale_shape_manual(
  values = c(18, 15, 18, 17),
  name = "Treatment",
  labels = c(
    "Control",
    expression(MET['0-8wks']),
    expression(MET['0-4wks']),
    expression(MET['4-8wks'])
  )
))

方法2:用parse批量解析文本(更简洁)

如果标签格式统一,可通过parse(text = ...)批量生成表达式向量,代码更简洁:

point_4 <- list(scale_shape_manual(
  values = c(18, 15, 18, 17),
  name = "Treatment",
  labels = parse(text = c(
    "Control",
    "MET[0-8wks]",
    "MET[0-4wks]",
    "MET[4-8wks]"
  ))
))

同步多美学属性的图例标签

你的ggplot aes同时绑定rx到color、linetype、shape三个属性,为保证所有图例标签一致,建议统一设置对应scale参数:

# 定义统一的标签向量
treatment_labels <- parse(text = c(
  "Control",
  "MET[0-8wks]",
  "MET[0-4wks]",
  "MET[4-8wks]"
))

# 批量设置所有关联的scale
scales <- list(
  scale_shape_manual(values = c(18,15,18,17), name = "Treatment", labels = treatment_labels),
  scale_color_manual(name = "Treatment", labels = treatment_labels, values = c("#000000", "#E69F00", "#56B4E9", "#009E73")), # 自行补充颜色值
  scale_linetype_manual(name = "Treatment", labels = treatment_labels, values = c(1,2,3,4)) # 自行补充线型值
)

# 绘图时加载统一设置
graph <- ggplot(data=mydata, aes(x=weeks, y=bw, group = rx, color = rx, linetype = rx, shape = rx))+
  stat_summary(fun = "mean", geom = "line", lwd = rel(1))+
  stat_summary(fun = mean,
               geom = "pointrange",
               fun.max = function(x) mean(x) + sd(x) / sqrt(length(x)),
               fun.min = function(x) mean(x) - sd(x) / sqrt(length(x)))+
  stat_summary(fun = "mean", geom = "point", size = rel(2), fill = "white", stroke = rel(1.1))+
  ggtitle("Title")+
  labs(subtitle = " ", x = " Age (Weeks) ", y = "Body Mass (g)") +
  scale_x_discrete(labels = c("5","6", "7", "8", "9","10", "11", "12", "13", "14","15","16","17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27"))+
  line_graph_4_theme2()+
  scales
graph

内容的提问来源于stack exchange,提问作者KC-learning-stats

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:13:10