0

我有一个数据框,其中包含按日期衡量的生产力。日期从 2013 年 5 月 4 日到 2014 年 7 月 11 日。生产力衡量标准针对 6 个组织单位

数据如下所示:

> str(prods)
'data.frame':   588 obs. of  6 variables:
 $ SOM  : Factor w/ 7 levels "BVG1 Scotland",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Skill: Factor w/ 1 level "A": 1 1 1 1 1 1 1 1 1 1 ...
 $ Date : Date, format: "2013-04-05" "2013-04-12" "2013-04-19" "2013-04-26" ...
 $ Prod : num  2.97 2.94 2.87 2.95 2.97 2.97 2.97 2.94 2.86 2.98 ...
 $ Month: num  4 4 4 4 5 5 5 5 5 6 ...
 $ Year : num  2013 2013 2013 2013 2013 ...

概括:

> summary(prods)
                           SOM     Skill        Date                 Prod           Month            Year     
 BVG1 Scotland               :84   A:588   Min.   :2013-04-05   Min.   :2.370   Min.   : 1.00   Min.   :2013  
 BVG11 Highlands & IslandsA  :84           1st Qu.:2013-08-28   1st Qu.:2.888   1st Qu.: 4.75   1st Qu.:2013  
 BVG12 North East ScotlandA  :84           Median :2014-01-20   Median :3.030   Median : 7.00   Median :2014  
 BVG13 Central ScotlandA     :84           Mean   :2014-01-20   Mean   :3.029   Mean   : 6.75   Mean   :2014  
 BVG14 South East ScotlandA  :84           3rd Qu.:2014-06-14   3rd Qu.:3.180   3rd Qu.: 9.00   3rd Qu.:2014  
 BVG15 West Central ScotlandA:84           Max.   :2014-11-07   Max.   :3.510   Max.   :12.00   Max.   :2014  
 BVG16 South West ScotlandA  :84                                                                              

我只是想使用显示 2013 年和 2014 年的 ggplot2 绘制线图,"Prod" 我可以绘制迄今为止的实际产品,如下所示: 在此处输入图像描述

我使用的代码是:

ggplot(prods, aes(x = Date, y = Prod, group = SOM)) + 
     geom_line(lwd = 1.3, colour = "red") +
     ylab("Actual Productivity") + theme(axis.title.x=element_blank()) +
     facet_wrap(~ SOM)

最好按年份显示产品,例如 2013 年的紫色线和 2014 年的红色线。

任何帮助将不胜感激。

问候,

这就是我所做的:

ggplot(prods[Year==2013,], aes(x = Date, y = Prod, group = SOM)) + 
 geom_line(lwd = 1.3, colour = "purple") +
 ylab("Actual Productivity") + theme(axis.title.x=element_blank()) +
 geom_line(data=prods[Year==2014,], aes(x = Date, y = Prod, group = SOM),lwd = 1.3, colour = "red") +
        scale_color_manual("Period", values = c("purple","red"), labels = c("2013","2014")) +
 facet_wrap(~ SOM)

我没有收到任何错误,但图像上没有弹出图例。它看起来像这样: 在此处输入图像描述

4

1 回答 1

0
 prods <- data.frame(Prod=c(1:10,1:10),
                     Date=rnorm(20),
                     year=rep(c(2013,2014,2013,2014),each=5),
                     SOM=rep(letters[1:2],each=10))

上面制作假数据,然后在一年的子集下面编码。您不必像我一样制作年份列,您可以在实际数据列本身上进行子集化。下图为 2013 年和 2014 年一次。

ggplot(prods[prods$year==2013,], aes(x = Date, y = Prod, group = SOM)) + 
 geom_line(lwd = 1.3, colour = "purple") +
 geom_line(data=prods[prods$year==2014,], 
           aes(x = Date, y = Prod, group = SOM),lwd = 1.3, colour = "red") +
 ylab("Actual Productivity") + 
 theme(axis.title.x=element_blank()) +
 facet_wrap(~ SOM)

在此处输入图像描述

于 2014-11-12T13:40:12.240 回答