1
dput(x)
structure(list(Date = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L), .Label = c("1/1/2012", "2/1/2012", "3/1/2012"
), class = "factor"), Server = structure(c(1L, 2L, 3L, 4L, 1L, 
2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"), 
    Storage = c(10000L, 20000L, 30000L, 15000L, 15000L, 25000L, 
    35000L, 15700L, 16000L, 27000L, 37000L, 16700L)), .Names = c("Date", 
"Server", "Storage"), class = "data.frame", row.names = c(NA, 
-12L))

我想创建一个堆栈栏 x=Date, y=Storage 并根据总存储量放置一条线性线。

我想出了这条 ggplot 行:

ggplot(x, aes(x=Date, y=Storage)) + geom_bar(aes(x=Date,y=Storage,fill=Server), stat="identity", position="stack") + geom_smooth(aes(group=1),method="lm", size=2, color="red")

它有点工作,但线性线不是基于日期框架 x 上给定日期的总存储量。是否有捷径可寻?

4

1 回答 1

1

通常最简单的方法就是计算 ggplot2 之外的值。所以计算总数:

dd = as.data.frame(tapply(x$Storage, x$Date, sum))
dd$Date = rownames(dd)
colnames(dd)[1] = "Storage"

然后添加一个geom_smooth调用但指定数据:

ggplot(x, aes(x=Date, y=Storage)) + 
    geom_bar(aes(x=Date,y=Storage, fill=Server), stat="identity", position="stack") + 
    geom_smooth(data = dd, aes(x=Date, y=Storage, group=1),method="lm")
于 2013-02-04T14:59:28.127 回答