R 4.2.2中ggplot坐标轴科学计数法×符号显示异常的解决
解决R 4.2.2中ggplot科学计数法乘号显示为空方块的问题
只需调整自定义的scientific标签函数,将原本的%*%替换为ggplot表达式兼容的\times(LaTeX标准乘号),即可适配R 4.2.2版本的渲染逻辑,实现5.3 × 10^7格式的数值显示。
修改后的完整脚本如下:
value <- c(24000000, 30000000) Station <- c("A", "B") SD <- c(15000000, 17000000) datatest2 <- data.frame(Station, value, SD) # 修改此处的替换逻辑,用\\times替代%*% scientific <- function(x){ ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", " \\times 10^", scientific_format()(x))))) } tt <- ggplot(datatest2, aes(y=value, x=Station)) + geom_bar(position=position_dodge(width=0.9), stat="identity", fill = c("A"="khaki1", "B"="khaki4")) + geom_text(label = c("a", "a"), aes(y = c(50000000, 50000000), x = c(1, 2)), size = 6) + ylab(expression(paste("Value", sep=""))) + xlab(expression(paste("Sampling station", sep=""))) + scale_x_discrete(guide = ggplot2::guide_axis(n.dodge = 1), labels = function(x) stringr::str_wrap(x, width = 15)) + geom_errorbar(aes(x=Station, ymin=value-SD, ymax=value+SD),position=position_dodge(width=0.9), alpha=0.9, width=0.4, colour="black", size=1) + theme_classic() + coord_cartesian(ylim = c(0,53000000)) + scale_y_continuous(expand = c(0,0), label = scientific) + theme(axis.text=element_text(size=18, colour = 'black'), axis.title=element_text(size=18, colour = "black"), axis.line = element_line(colour = 'black', size = 1), axis.ticks = element_line(size = 1), axis.ticks.length=unit(.25, "cm"), axis.title.x = element_text(margin=margin(t=20), colour = 'black'),axis.title.y = element_text(margin=margin(r=25)), legend.justification=c(1.5,0.5), legend.position="bottom", legend.background = element_rect(fill="white", size=18, linetype="dotted"), legend.text=element_text(size=18, margin=margin(r=55)), legend.title=element_text(colour = "white", size = 0)) tt
关键修改说明
在scientific函数中,将gsub("e", "%*% 10^", ...)替换为gsub("e", " \\times 10^", ...):
\\times是ggplot表达式解析时识别的LaTeX乘号,在R 4.2.2版本中渲染兼容性更好,不会出现字体缺失导致的空方块问题- 保留原有的
gsub("[+]", "", ...)逻辑,用于去除科学计数法中的正号
内容的提问来源于stack exchange,提问作者AnnanasImp
相关产品推荐
相关产品推荐

