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

R Markdown中第二张散点图LOESS线无法显示的原因及解决方法

问题描述

在R Markdown的同一代码块中,使用lead和lead2两个数据框创建并排散点图,第一张图可成功添加LOESS线,但第二张图的LOESS线无法显示。

原代码如下:

3.3 Scatterplot - lead-time to IF vs year of IF onset 

```{r,figures-side, fig.show="hold", out.width="50%"}

plot(lead$Yr,lead$leadtime, main="Leadtime by Year of Onset (reg-filled)",
   xlab="Year of Onset", ylab="Leadtime (Years)", pch=19)
lines(lowess(lead$IF_Yr,lead$leadtime), col="red") # lowess line (x,y)


plot(lead2$Yr,lead2$leadtime,main="Leadtime by Year of Onset (exc missing)",
   xlab="Year of Onset", ylab="Leadtime (Years)", pch=19)
lines(lowess(lead2$IF_Yr,lead2$leadtime), col="red") # lowess line (x,y)
# 问题原因
第二张图的`lowess()`函数使用的x轴变量是`lead2$IF_Yr`,但对应的散点图`plot()`调用时用的x轴变量是`lead2$Yr`,两者变量不匹配(或数值范围差异大),导致LOESS拟合的结果超出了散点图的x轴显示范围,因此线条无法显示。

第一张图能正常显示LOESS线,是因为`lead`数据框中的`Yr`和`IF_Yr`为同一变量(或数值范围完全重叠),拟合的线条刚好落在散点图的显示范围内。

# 修改后的代码
### 方案一:统一x轴变量(推荐)
将第二张图`lowess()`中的x变量改为与`plot()`一致的`lead2$Yr`,确保x轴变量统一:
```r
3.3 Scatterplot - lead-time to IF vs year of IF onset 

```{r,figures-side, fig.show="hold", out.width="50%"}

plot(lead$Yr,lead$leadtime, main="Leadtime by Year of Onset (reg-filled)",
   xlab="Year of Onset", ylab="Leadtime (Years)", pch=19)
lines(lowess(lead$Yr,lead$leadtime), col="red") # 统一使用Yr作为x变量


plot(lead2$Yr,lead2$leadtime,main="Leadtime by Year of Onset (exc missing)",
   xlab="Year of Onset", ylab="Leadtime (Years)", pch=19)
lines(lowess(lead2$Yr,lead2$leadtime), col="red") # 统一使用Yr作为x变量
### 方案二:手动扩展x轴范围
如果确实需要用`IF_Yr`作为LOESS拟合的x轴,可在`plot()`中添加`xlim`参数手动设置包含两个变量的范围:
```r
3.3 Scatterplot - lead-time to IF vs year of IF onset 

```{r,figures-side, fig.show="hold", out.width="50%"}

plot(lead$Yr,lead$leadtime, main="Leadtime by Year of Onset (reg-filled)",
   xlab="Year of Onset", ylab="Leadtime (Years)", pch=19)
lines(lowess(lead$IF_Yr,lead$leadtime), col="red")


plot(lead2$Yr,lead2$leadtime,main="Leadtime by Year of Onset (exc missing)",
   xlab="Year of Onset", ylab="Leadtime (Years)", pch=19,
   xlim = range(c(lead2$Yr, lead2$IF_Yr))) # 扩展x轴范围包含IF_Yr
lines(lowess(lead2$IF_Yr,lead2$leadtime), col="red")
内容的提问来源于stack exchange,提问作者Hong
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:11:16