基于 ggplot2 中的子集的黄土平滑器

3

我正在处理一些图表,其中最后两个点不是最新的。这导致低数字拉低了我的平滑线。

dat1<-data.frame(vals=c(30,40,50,30,40,50,30,10,5),
                 q.year=c("q1 09", "q2 09", "q3 09", "q4 09", "q1 10", "q2 10", "q3 10", "q4 10", "q1 11"),
                 dummy=rep("g1", 9)
)
dat1$q.year<-factor(dat1$q.year, unique(dat1$q.year))

ggplot(dat1, aes(x=q.year, y=vals, group=dummy))+
  geom_point()+
  geom_line()+
  geom_smooth(method="loess", se=FALSE, lty=2)

我想绘制平滑曲线,但不包括两个低点。我可以使用子集完成此操作。
gg1<-ggplot(dat1, aes(x=q.year, y=vals, group=dummy))+
  geom_point()+
  geom_line()+
  geom_smooth(data=subset(dat1, q.year %in% levels(q.year)[1:7]),
              method="loess", se=FALSE, lty=2)
print(gg1)

但是,当涉及到使用新数据重复使用情节时(即gg2<- gg1 %+% someMoreData),我不得不再添加一行来对新数据集(someMoreData)进行子集剪裁。

有没有更好的方法来做这件事?我能否引用已传递到情节中的数据?

如果问题不太清楚,请原谅 - 如有需要将更新

谢谢


我不确定有没有绕过这个问题的方法,而不是只是创建图形而不使用 geom_smooth 层,然后在决定是否需要对数据进行子集操作后再添加它。 - joran
1个回答

2
fun <- function(val,fac,n) {val[fac %in% tail(levels(fac),n)] <- NA; val}

gg1a <- ggplot(dat1, aes(x=q.year, y=vals, group=dummy))+
  geom_point()+
  geom_line()+
  geom_smooth(aes(x=q.year,y=fun(vals,q.year,2)),
              method="loess", se=FALSE, lty=2)
print(gg1a)
#Warning message:
#Removed 2 rows containing missing values (stat_smooth).

dat2<-data.frame(vals=c(50,40,50,30,40,50,30,10,5,5),
                 q.year=c("q1 09", "q2 09", "q3 09", "q4 09", "q1 10", "q2 10", "q3 10", "q4 10", "q1 11","q2 11"),
                 dummy=rep("g1", 10)
)
#make sure that your factor is ordered, 
#otherwise it gets reordered by ggplot according to levels
dat2$q.year <- factor(as.character(dat2$q.year),levels=as.character(dat2$q.year),ordered = TRUE)

gg1a %+% dat2
#Warning message:
#Removed 2 rows containing missing values (stat_smooth).

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接