2016-02-16 30 views
2

假設我收集Stack Overflow中的帖子,並將它們分爲N個類別。我的目標是每天繪製N個百分比,並且每天繪製一個帖子總數。ggplot2:在每個x處添加組值的總和

要玩,我會使用玩具數據框。我可以繪製每天每個類別的百分比:

data(beav1) 
beav1$day <- as.factor(beav1$day) 
beav1[beav1$day==346,]$time <- 1:sum(beav1$day==346) 
beav1[beav1$day==347,]$time <- 1:sum(beav1$day==347) 
beav1 <- filter(beav1, time<23) 
ggplot(beav1, aes(x=time, y=temp, group=day, fill=day, color=day)) + 
    geom_line() 

enter image description here

但我怎麼可以添加符合總溫度是多少?或者是什麼意思?

編輯:與this other question的不同之處在於,我希望所有組的單行都有一行,而不是每行一行。

數據集

dput(beav1) 
structure(list(day = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L), .Label = c("346", "347"), class = "factor"), 
    time = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
    13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 1L, 2L, 
    3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 
    16L, 17L, 18L, 19L, 20L, 21L, 22L), temp = c(36.33, 36.34, 
    36.35, 36.42, 36.55, 36.69, 36.71, 36.75, 36.81, 36.88, 36.89, 
    36.91, 36.85, 36.89, 36.89, 36.67, 36.5, 36.74, 36.77, 36.76, 
    36.78, 36.82, 36.93, 36.83, 36.8, 36.75, 36.71, 36.73, 36.75, 
    36.72, 36.76, 36.7, 36.82, 36.88, 36.94, 36.79, 36.78, 36.8, 
    36.82, 36.84, 36.86, 36.88, 36.93, 36.97), activ = c(0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA, 
-44L), .Names = c("day", "time", "temp", "activ")) 
+3

的可能的複製[如何添加水平線表示在GGPLOT2所有羣體的手段?(http://stackoverflow.com/questions/32504313/如何添加水平線顯示手段爲所有組在ggplot2) –

+0

鏈接的帖子要求「每組」意味着,當我要求整體意味着(我想要一條線,而不是N) – alberto

+0

可能的重複[在ggplot2中添加一條水平線到圖和圖例](http://stackoverflow.com/questions/13254441/add-a-horizo​​ntal-line-to-plot-and-legend-in-ggplot2 ) –

回答

2

好了,通知說groupfillcolor不是ggplot但在geom_line,這樣你可以使用stat_summary不需要重新定義組。

ggplot(beav1, aes(x=time, y=temp)) + 
    geom_line(aes(group=day, fill=day, color=day))+ 
    stat_summary(fun.y = mean, na.rm = TRUE, group = 3, color = 'black', geom ='line') 

如果你想的和公正的地方fun.y = sum

+0

就是這樣!所以這是一個填補和顏色在正確的地方!謝謝! – alberto

+0

不用客氣 –

+0

這很棒,但新的'全部'系列沒有出現在圖例中。如何添加? –