如何在ggplot的x轴文本中显示下标、希腊字母及特殊符号?
你遇到的报错核心原因是x轴映射的grp变量为数值类型,ggplot默认将其识别为连续型坐标轴,调用scale_x_discrete自然会触发类型不匹配的错误。可按以下步骤修改实现x轴下标、希腊字母等特殊格式的渲染:
步骤1:调整x轴映射为分类型
将ggplot代码中aes的x参数改为因子类型,显式声明为离散坐标轴:
ggplot(data = t, aes(x = factor(grp), y = b.hat, group = geo.l))
步骤2:生成动态可解析标签
你之前的expression写法无法正确插入动态计算的数值,可以直接生成符合plotmath语法的字符向量,后续交给官方工具解析即可:
grp <- unique(temp[,c('b.g.l', 'b.g.l.se', 'b.g.h', 'b.g.h.se')]) # 生成每个标签的字符内容,符合plotmath语法 lab_chr <- sapply(1:nrow(grp), function(i) { l_low <- round(grp$b.g.l[i] - grp$b.g.l.se[i], 2) l_high <- round(grp$b.g.l[i] + grp$b.g.l.se[i], 2) h_low <- round(grp$b.g.h[i] - grp$b.g.h.se[i], 2) h_high <- round(grp$b.g.h[i] + grp$b.g.h.se[i], 2) sprintf("list(U['[%s,%s]'], U['[%s,%s]'])", l_low, l_high, h_low, h_high) }) # 给标签命名,和factor(grp)的水平一一对应 names(lab_chr) <- unique(t$grp)
步骤3:修改x轴刻度配置
替换你之前添加的scale_x_discrete(labels = lab)为如下代码,用label_parsed(和分面用的解析工具一致)将字符转为数学表达式渲染:
scale_x_discrete(labels = lab_chr, label = label_parsed)
完整修改后代码
ggplot(data = t, aes(x = factor(grp), y = b.hat, group = geo.l)) + geom_hline(yintercept = unique(temp$b), lty='dotted', color = 'gray20') + geom_point(aes(color = geo.l), position = position_dodge(width = 1)) + geom_errorbar(aes(ymin = b.hat - 2 * b.hat.se, ymax = b.hat + 2 * b.hat.se, color = geo.l), alpha = 0.75, width = 0, position = position_dodge(width = 1)) + labs(x = '', y = "Estimates") + scale_color_manual(name = "Threshold", values = c('skyblue3', 'royalblue3', 'navyblue')) + # 新增x轴配置 scale_x_discrete(labels = lab_chr, label = label_parsed) + facet_wrap(~sn, labeller = label_parsed) + theme_classic() + theme(legend.position = "bottom", axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.title = element_blank(), panel.border = element_rect(colour = "black", fill=NA, size=0.5))
内容的提问来源于stack exchange,提问作者Dai
相关产品推荐
相关产品推荐

