绘制每半小时的数据

时间:2015-10-26 13:34:32

标签: r

我的数据如下:

> operation_time      nb_reaction
> 13.02                  14
> 13.08                  4
> 13.58                  17
> 14.02                  36
> 14.09                  44
> 14.52                  64
> 15.03                  78

我想绘制(在条形图中)这些数据x =时间和y = nb_reaction,例如通过每30分钟对它们进行分组,例如13.02和13.08将包含在同一个条形图中,之后的第二个半小时在14.02和14.09之后将包含13.58 onlyr。

怎么做?

非常感谢

1 个答案:

答案 0 :(得分:1)

假设您的两列都是数字的,您可以这样做:

#this function returns the decimal of a number
decimal <- function(x) {

  decs <- as.numeric(substr(format(x,2), 4,5))
  decs

}

然后使用上面的函数来计算时间:

#Just an ifelse function to round the time to either .00 or .30
df$round_time <- ifelse(decimal(df$operation_time) < 30, 
                        df$operation_time - decimal(df$operation_time) / 100, 
                        df$operation_time - decimal(df$operation_time) / 100 + 0.30)

然后汇总以下内容:

toplot <- aggregate(nb_reaction ~ round_time, data=df, FUN=sum)

最后的情节:

barplot(toplot$nb_reaction, names.arg=as.character(toplot$round_time) )

enter image description here

P.S。如果您愿意,可以在上面的names.arg上提供自己的标签。

相关问题