你如何在ggplot2中的geom_bar上创建线性线

时间:2015-10-28 19:53:13

标签: r ggplot2

我需要创建堆叠的ggplot条形图给定此数据集,并绘制线性线:

        dput(t)
structure(list(Date = structure(c(16436, 16436, 16436, 16467, 
16467, 16467, 16467, 16467, 16679, 16679, 16679, 16679, 16679
), class = "Date"), Applicatio = structure(c(4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L), .Label = c("DB", "Opt", 
"Tom", "Web"), class = "factor"), Code = structure(c(1L, 2L, 
4L, 3L, 1L, 2L, 4L, 3L, 3L, 1L, 2L, 4L, 3L), .Label = c("ch", 
"db", "tt", "zz"), class = "factor"), m = structure(c(1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("2015-01", 
"2015-02", "2015-09"), class = "factor"), count = c(1L, 3L, 1L, 
4L, 1L, 7L, 1L, 9L, 1L, 6L, 4L, 7L, 9L), Total = c(1L, 12L, 1L, 
2L, 1L, 20L, 1L, 7L, 7L, 9L, 50L, 3L, 6L)), .Names = c("Date", 
"Applicatio", "Code", "m", "count", "Total"), row.names = c(NA, 
-13L), class = "data.frame")

我正在尝试这个:

ggplot(subset(t, Date> as.Date(c("2015-01-01", format="%Y-%m-%d"))), aes(m,fill=Code))+geom_bar()+
  geom_smooth(aes(m,Total),method="lm", se=FALSE)+
        guides(colour=FALSE)

1 个答案:

答案 0 :(得分:1)

我不完全确定你想要实现的目标,但看起来你想要这个:

ggplot(subset(t, Date > as.Date("2015-01-01", format="%Y-%m-%d")), aes(m,fill=Code))+geom_bar()+
  geom_smooth(aes(m,Total,group=1),method="lm", se=FALSE)+
  guides(colour=FALSE)

基本上,您在c函数中有一个subset函数,不需要,然后您需要在group=1函数中使用geom_smooth,如警告所述

enter image description here

所以,是的,你可以在geom_bar上有一条直线。