r 堆积条总值

r stacked bar total value

我想创建一个关于从房屋(房屋中的设备)收集的数据的图 (EDA)。但是我卡住了..

数据看起来像这样:

df$device    df$date       df$time    df$value
boiler       2015-01-13    12:15      0.0009
boiler       2015-01-13    12:30      0.0007
boiler       2015-01-13    12:45      0.0005
boiler       2015-01-13    13:00      0.0010
TV           2015-01-13    12:15      0.0009
TV           2015-01-13    12:30      0.0007
TV           2015-01-13    12:45      0.0005
TV           2015-01-13    13:00      0.0010
boiler       2015-01-14    12:15      0.0009
boiler       2015-01-14    12:30      0.0007
boiler       2015-01-14    12:45      0.0005
boiler       2015-01-14    13:00      0.0010
TV           2015-01-14    12:15      0.0009
TV           2015-01-14    12:30      0.0007
TV           2015-01-14    12:45      0.0005
TV           2015-01-14    13:00      0.0010

数据是在 8 个月(1 月至 9 月)内测得的。我想制作一个情节,其中: Y 轴 = 测量值 X 轴 = 月 图 = 所有设备

我尝试过:

df$monthnumber <- month(df$Date)
test <- table(df$Device, df$monthnumber)

barplot(counts1,col=rainbow(7), xlim = c(1,15),
        legend = c(rownames(counts1)), bty = "L") 

导致下一张图片的原因:

结果: 但是,那是错误的。因为它包含测量设备的频率。我不知道如何为每个应用程序添加每个月的总值(总和)。

我试过了:

test$value <- aggregate (df$Measurevalue, by = list(genergy$Device), sum)

但是报错:

Error in $<-.data.frame(tmp, "value", value = list(Group.1 = c("Boiler", :
replacement has 7 rows, data has 285896

我该如何解决这个问题? - 一个堆叠条,每个设备的总价值,以及 (y= energy), (X= months)

因此,您可以结合使用 dplyrggplot

library("dplyr")
library("ggplot2")

df <- data.frame(device = c("boiler","boiler","boiler","boiler","TV","TV","TV","TV","boiler","boiler","boiler","boiler","TV","TV","TV","TV"), 
                     date = c("2015-01-13","2015-01-13","2015-01-13","2015-01-13","2015-01-13","2015-01-13","2015-01-13","2015-01-13","2015-01-14","2015-01-14","2015-01-14","2015-01-14","2015-01-14","2015-01-14","2015-01-14","2015-01-14"),
                     time = c("12:15","12:30","12:45","13:00","12:15","12:30","12:45","13:00","12:15","12:30","12:45","13:00","12:15","12:30","12:45","13:00"),
                     value = c(0.009,0.007,0.005,0.001,0.009,0.007,0.005,0.001,0.009,0.007,0.005,0.001,0.009,0.007,0.005,0.001)
                     )
    df <- mutate(df,device = as.factor(device),
                 date = as.Date.character(date,format = "%Y-%m-%d")) %>%
      group_by(device) %>%
        mutate(sum(value))

结果是每天按设备汇总

正如您在评论中提到的,您希望每月进行一次 - 根据月份 table 分组

df<- group_by(df,m=as.factor(month(date)),device) %>%
summarise(s = sum(value))
ggplot(df,aes(x=m,y=s,fill=device)) + geom_bar(stat="identity")

因为,我没有足够的月度数据,图表看起来如下..

更新:27/06/2016 输入数据后,您 运行 以下命令。然后尝试根据月份汇总数据。

    df <- mutate(df,device = as.factor(device),
                  date = as.POSIXct((strftime(date,format = "%Y-%m-%d")))) %>%
         group_by(device)