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

双Y轴ggplot图表geom_smooth使用loess无置信区间问题求解

问题原因

  • geom_smooth的置信区间使用fill参数控制填充样式,你当前仅对线条颜色color做了分组映射和手动赋值,没有配置对应的fill映射,导致置信区间无有效填充色、无法显示。
  • scale_color_manual传入了4个色值,但实际仅存在2个分组(Vix PU 178、OT PU 178),色值数量和分组不匹配也会引发样式渲染异常。
  • 额外注意:代码中使用attach(Dati)易造成全局变量污染,ggplot本身支持从传入的data对象中直接读取变量,无需提前attach。

修正后代码

library(ggplot2)

Dati  <- data.frame("r" = c(0.99, 1.42, 2.10, 3.32, 6.09), 
                    "Vix" = c(16500, 19200, 22500, 24000, 26000), 
                    "OT" = c(23.5, 19, 11, 9, 7), 
                    "ref" = c("PU 178", "PU 178", "PU 178", "PU 178", "PU 178"))

scaleFactor <- max(Dati$Vix) / max(Dati$OT)

Graph <- ggplot(Dati, aes(x= r)) +
  geom_point(aes(y= Vix, col=paste0("Vix ", ref)), shape = 1, size = 3.5) +
  # 新增fill映射,和color保持同分组
  geom_smooth(aes(y= Vix, col = paste0("Vix ", ref), fill = paste0("Vix ", ref)),  
              method="loess", level=0.55, se = TRUE, alpha = 0.2) +  
  geom_point(aes(y= OT * scaleFactor, col=paste0("OT ", ref)), shape = 1, size = 3.5) + 
  # 新增fill映射,和color保持同分组
  geom_smooth(aes(y=OT * scaleFactor, col = paste0("OT ", ref), fill = paste0("OT ", ref)), 
              method="loess", level=0.55, se = TRUE, alpha = 0.2) +  
  # 同时配置color和fill的手动色值,2个分组对应2组色值
  scale_color_manual(values=c('#644196', '#f92410'), name = "") +
  scale_fill_manual(values=c('#644196', '#f92410'), name = "") +
  theme(legend.justification = "top") +
  scale_y_continuous(name="Viscosity at 10rpm (mPa s)", 
                     sec.axis=sec_axis(~./scaleFactor, name="open time (sec)")) +
  theme(
    axis.title.y.left=element_text(color='#f92410'),
    axis.text.y.left=element_text(color='#f92410'),
    axis.title.y.right=element_text(color='#644196'),
    axis.text.y.right=element_text(color='#644196'),
    legend.position = "none"
  ) + 
  scale_x_continuous(name="ratio A2333/AD5027") 

Graph

效果验证

运行修正后代码即可看到两条loess拟合线对应的半透明置信区间,alpha参数可调整置信区间的透明度,按需修改即可。

内容的提问来源于stack exchange,提问作者GiacomoDB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:45:01