R语言使用ggplot绘图时显示≥、≤符号及上标的问题求解
解决方案
两个问题的核心原因是你使用expression后没有配置ggplot对y轴标签的表达式解析逻辑,只要在scale_y_discrete中增加标签解析配置即可同时解决上标和不等号显示的需求。
方案1:修改原始因子水平(推荐,可扩展性高)
先修改mydata中term因子的水平为plotmath可解析的格式,绘图时指定解析标签即可:
# 替换因子水平为plotmath可识别格式 levels(mydata$term) <- c( "Age~(years)", "Sex~(male)", "Never~smoker~(reference)", "Current~smoker", "Former~smoker", "Obesity", "BMI~(kg/m^2)", # 上标语法直接写在字符串中 "Diabetes", "Glucose~(mmol/L)", "Glucose~lowering~medication~use", "Hypertension", "Systolic~blood~pressure~(mmHg)", "Diastolic~blood~pressure~(mmHg)", "Antihypertensive~medication~use", "Hypercholesterolemia", "LDL~cholesterol~(mmol/L)", "Lipid~lowering~medication~use", ">=90~(reference)", # plotmath中>=自动渲染为≥ "60-89", "<=60" # plotmath中<=自动渲染为≤ ) # 绘图代码仅需修改scale_y_discrete部分 ggplot(data=mydata, aes(x=estimate, y=fct_rev(term))) + geom_point() + geom_errorbarh(aes(xmin=conf_low, xmax=conf_high, height=0.15)) + annotation_custom(grob=grid::textGrob(label="Chronic kidney disease", gp=grid::gpar(fontface="bold", fontsize=11), hjust=1.0), xmin=-Inf, xmax=-Inf, ymin=3.2, ymax=3.2) + coord_cartesian(clip="off") + #scale_x_continuous(expand=expansion(mult=c(.05, .3))) + theme(axis.text.y=element_text(margin=margin(t=0, r=2.2, b=0, l=40, "pt"))) + scale_y_discrete(name="", labels = ~parse(text = .x)) # 新增解析标签的配置
方案2:不修改原始数据,直接在绘图时转换标签
如果不想改动原始数据,可以直接在scale_y_discrete的labels参数中自定义转换函数:
library(stringr) ggplot(data=mydata, aes(x=estimate, y=fct_rev(term))) + geom_point() + geom_errorbarh(aes(xmin=conf_low, xmax=conf_high, height=0.15)) + annotation_custom(grob=grid::textGrob(label="Chronic kidney disease", gp=grid::gpar(fontface="bold", fontsize=11), hjust=1.0), xmin=-Inf, xmax=-Inf, ymin=3.2, ymax=3.2) + coord_cartesian(clip="off") + #scale_x_continuous(expand=expansion(mult=c(.05, .3))) + theme(axis.text.y=element_text(margin=margin(t=0, r=2.2, b=0, l=40, "pt"))) + scale_y_discrete(name="", labels = function(x) { # 替换需要特殊渲染的字符 x <- str_replace_all(x, " ", "~") # plotmath空格用~代替 x <- str_replace(x, "kg/m\\^2", "kg/m^2") x <- str_replace(x, ">90", ">=90") x <- str_replace(x, "<60", "<=60") parse(text = x) })
注意事项
- 若运行后出现符号乱码,可以在theme中指定支持的字体,比如增加
theme(text = element_text(family = "Microsoft YaHei"))适配Windows系统的字体渲染。 - 你提供的示例数据中BMI项的
conf_low(1.4)大于conf_high(0.6),会导致误差条方向异常,可先对数据做修正:
mydata <- mydata %>% mutate( temp = pmin(conf_low, conf_high), conf_high = pmax(conf_low, conf_high), conf_low = temp )
内容的提问来源于stack exchange,提问作者tcvdb1992
相关产品推荐
相关产品推荐

