【问题标题】:Applying different geom functions in a ggplot在 ggplot 中应用不同的几何函数
【发布时间】:2014-03-12 18:01:35
【问题描述】:

我正在努力绘制一个 ggplot,我需要在某个时间点后更改 geom_smooth。就像现在一样,我正在为整个系列应用平滑功能,但平滑线对于“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)

【问题讨论】:

  • 如何将您的数据对象放入每个单独的 geom 调用中?即 geom_rect(data,aes(.... 那么对于 geom_smooth 调用,只需为您希望绘制的适当部分的数据子集 ... g+geom_smooth(data[rowsIwant, ],aes(....
  • @user3407340 你能提供一些数据吗?

标签: r ggplot2


【解决方案1】:

我将尝试回答,以便至少从这里开始。我认为,您想要做的是您有兴趣绘制所有点,但在数据点(您的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")

结果是这样的:

这是朝着正确的方向吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2015-04-03
    • 2011-12-15
    • 1970-01-01
    • 2018-03-16
    • 2017-10-04
    相关资源
    最近更新 更多