ggplot2:在每个x处添加一行以表示组值之和 [英] ggplot2: add line for sum of group values at each x

查看:112
本文介绍了ggplot2:在每个x处添加一行以表示组值之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我收集了Stack Overflow中的帖子,并将它们归类为N个类别.我的目标是绘制每天的N百分比,并在每天的总帖子数上画一条线.

Let's say I collect the posts in Stack Overflow and I classify them in N categories. My goal is to plot the N percentage every day and a line with the total number of posts per day.

要使用,我将使用玩具数据框.我可以绘制每天每种类别的百分比:

To play with, I'll use a toy dataframe. I can plot the percentage of every category per day:

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()

但是如何将线路与总温度相加呢?还是这个意思?

But how can I add the line with the total temperature? Or the mean?

编辑:与

Edit: The difference with this other question is that I would like one single line for all the groups and not a line per group.

数据集

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"))

推荐答案

好,请注意,groupfillcolor不在ggplot中,但在geom_line中,因此您可以使用stat_summary无需重新定义组.

Ok, notice that group, fill and color are not in ggplot but in geom_line, this way you can use stat_summarywithout redefining the groups.

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

这篇关于ggplot2:在每个x处添加一行以表示组值之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆