在ggplot中应用不同的geom函数

时间:2014-03-12 18:01:35

标签: r ggplot2

我正在努力策划一个ggplot,我需要在某个点之后改变geom_smooth。就像现在一样,我为整个系列应用了平滑功能,但是平滑线对于#x; xmin"之后的时期没有多大意义。所以,我想知道是否有办法解决这个问题,我无法进一步为该标记绘制geom_smooht。

library(ggplot2)

xmin <- as.Date("2012/10/08", "%Y/%m/%d") # Beginning and end of discontinuity
xmax <- as.Date("2012/11/01", "%Y/%m/%d")

data$brand <- factor(data$brand, levels = c("A","B","C", "Others", "Undecideds"))

g <- ggplot(data)
g <- g + geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "#D8D8D8", alpha = .01)
g <- g + geom_point(aes(x=Date, y=Rating, colour=brand, group=interaction(brand, Event)), size=3.5)
g <- g + scale_color_manual(values=c("#0066FF","#00B206","#FF0000","#FFFFCC", "#D0D0D0"))
g <- g + geom_smooth(data=data, aes(x=Date, y=Rating, colour=brand, group=interaction(brand, Event)), method="loess", size=2, se=F)
g <- g + theme(legend.position="bottom")
print(g)

1 个答案:

答案 0 :(得分:0)

我会尝试一个答案,这样至少可以从这里开始。我想你要做的是,你有兴趣绘制所有点,但是在数据点(你的xmax)之后关注平滑近似。

所以这就是:

library(ggplot2)

xmin <- as.Date("2012/10/08", "%Y/%m/%d") # Beginning and end of discontinuity
xmax <- as.Date("2012/11/01", "%Y/%m/%d")

# dummy attempt to create some data to start
data=data.frame(brand=rep(c("A","B","C", "Others", "Undecideds"),100), 
            Date=seq(from=as.Date("2012/01/01", "%Y/%m/%d"), to=as.Date("2012/01/01", "%Y/%m/%d")+499, by="1 day"),
            Rating=runif(500),
            Event=rep(c('Event1','Event2'),250))


data$brand <- factor(data$brand, levels = c("A","B","C", "Others", "Undecideds"))
#Let's say that the data points after xmax are FWD, and the ones before, BCK
data$range=ifelse(data$Date>=xmax,"FWD","BCK")

ggplot() +
geom_rect(data=data,aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "#D8D8D8", alpha = .01) +
geom_point(data=data,aes(x=Date, y=Rating, colour=brand, group=interaction(brand, Event)), size=3.5) +
scale_color_manual(values=c("#0066FF","#00B206","#FF0000","#FFFFCC", "#D0D0D0")) +
# Smooth only the fwd ones
geom_smooth(data=data[data$range=="FWD",], aes(x=Date, y=Rating, colour=brand, group=interaction(brand, Event)), method="loess", size=2, se=F) +
theme(legend.position="bottom")

结果如下:

enter image description here

这是朝着正确的方向发展吗?