R语言ggtern 3.3.0与旧版三元填充等高线绘图代码适配问题
ggtern 3.3.0版本三元填充等高线图适配修改方案
报错核心成因
3.3.0版本ggtern调整了三元坐标系的图层兼容规则,是出现警告、图层被移除的直接原因:
- 原生ggplot2的二维密度图层(
stat_density2d、geom_density2d)不再被三元坐标系认可,加载到图中会直接被自动移除 - 密度计算所需的权重参数不再支持作为美学映射传入
aes(),写在映射内的参数会被识别为未知美学,直接忽略 - 新旧版本的统计函数传参逻辑存在差异,仅替换函数名不调整参数传递方式,会触发大量语法不兼容错误
具体调整内容
- 移除冗余映射:删掉
ggtern()初始化时重复嵌套的aes(x,y,z)映射项,避免触发新版ggtern的映射冲突检测报错 - 替换兼容图层:将不被三元坐标系认可的
stat_density2d、geom_density2d替换为ggtern专属的三元密度计算接口stat_density_tern、geom_density_tern,实现填充等高线与轮廓描边效果 - 修正参数传递逻辑:将原本写在
aes()内部的权重参数weight=d移出映射项,作为密度图层的独立计算参数传入,解决权重被识别为未知美学、直接忽略的问题 - 保留原有样式逻辑:对齐原代码的网格计算精度、等高线分箱宽度、黄红渐变色系、样本点与编号标注的设置,保证输出效果和参考样式完全一致
适配后可直接运行的代码
# 加载依赖包 library(ggplot2) library(ggtern) # 内置测试数据 a <- c(0.1, 0.5,0.5, 0.6, 0.2, 0 , 0 , 0.004166667, 0.45) b <- c(0.75,0.5,0 , 0.1, 0.2, 0.951612903,0.918103448, 0.7875 , 0.45) c <- c(0.15,0 ,0.5, 0.3, 0.6, 0.048387097,0.081896552, 0.208333333, 0.10) d <- c(500,2324.90,2551.44,1244.50, 551.22,-644.20,-377.17,-100, 2493.04) df <- data.frame(a, b, c, d) # 生成点标注ID df$id <- 1:nrow(df) # 适配新版语法的绘图逻辑 ggtern(data=df,aes(x=c,y=a,z=b)) + stat_density_tern(geom="polygon", n=400, weight = d, aes(fill=..level.., alpha=abs(..level..)), binwidth=100) + geom_density_tern(aes(color=..level..), n=400, weight = d, binwidth=100) + geom_point(aes(fill=d),color="black",size=5,shape=21) + geom_text(aes(label=id),size=3) + scale_fill_gradient(low="yellow",high="red") + scale_color_gradient(low="yellow",high="red") + theme_tern_rgbw() + theme(legend.justification=c(0,1), legend.position=c(0,1)) + guides(fill = guide_colorbar(order=1), alpha= guide_legend(order=2), color="none") + labs(title= "Ternary Plot and Filled Contour", fill = "Value, V",alpha="|V - 0|")
内容的提问来源于stack exchange,提问作者GiacomoDB
相关产品推荐
相关产品推荐

