将变量geom_hline添加到barplot的所有面 [英] Add variable geom_hline to all facets of a barplot

查看:297
本文介绍了将变量geom_hline添加到barplot的所有面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  plot<  -  qplot(Date,data = cns,
geom =bar,binwidth = 1,
fill = Type,facets = Name〜。)

这给了我一个名为barplot的小方块图。

cns的前11行看起来像:

 姓名日期类型天数
1姓名1 2013-03-12请求0
2姓名1 2013-03- 14请求0
3姓名1 2013-03-19请求0
4姓名2 2013-03-01已完成1
5姓名2 2013-03-01请求0
6名称2 2013-03-07已完毕3
7名称2 2013-03-08请求0
8姓名2 2013-03-08请求0
9姓名3 2013-03-08已完成0
10姓名3 2013-03-13请求0
11姓名3 2013-03-12已完成0

我想为每个方面添加一条水平线,平均天数(特定于方面或名称)。这也很复杂,因为Days列为所有类型'Requested'输入了0,这意味着要获得我正在寻找的意思,我真的希望 mean(cns $ Days)/(NROW (cns)/ 2)



我试过了:

  plot + geom_hline(aes(yintercept =(sum(cns $ Days)/(NROW(cns)/ 2))))

但是,正如我预期的那样,它会在每个方面放置一个相同值的水平线。我希望这条线是面向特定的,如果这是有道理的。



可以这样做吗?

解决方案

您可以在数据框中创建包含平均值的新列。我将它命名为 y.int ,并使用函数 ddply()从库 plyr 。此处的平均值仅针对 Type 已完成(如 Requested

  library(plyr)
cns< -ddply(cns,。( Name),transform,y.int = mean(Days [Type ==Completed]))

现在使用 geom_hline()和新列向每个方面添加行。

  plot + geom_hline(aes(yintercept = y.int))


I have a barplot using the ggplot2 library:

plot <- qplot(Date, data=cns, 
              geom="bar", binwidth = 1, 
              fill=Type, facets = Name ~ .)

Which gives me a faceted barplot, by name.

The first 11 rows of cns looks like:

            Name       Date      Type     Days
1           Name 1 2013-03-12 Requested    0
2           Name 1 2013-03-14 Requested    0
3           Name 1 2013-03-19 Requested    0
4           Name 2 2013-03-01 Completed    1
5           Name 2 2013-03-01 Requested    0
6           Name 2 2013-03-07 Completed    3
7           Name 2 2013-03-08 Requested    0
8           Name 2 2013-03-08 Requested    0
9           Name 3 2013-03-08 Completed    0
10          Name 3 2013-03-13 Requested    0
11          Name 3 2013-03-12 Completed    0

I would like to add a horizontal line to each facet, with the mean number of days (specific to the facet, or Name). This is also complicated because the column "Days" has 0s entered for all Type 'Requested', meaning that to get the mean I'm looking for I really want the mean(cns$Days)/(NROW(cns)/2).

I tried:

plot + geom_hline(aes(yintercept=(sum(cns$Days)/(NROW(cns)/2))))

But, as I sort of expected, it places a horizontal line of the same value in each of the facets. I would like the line to be facet-specific, if that makes sense.

Can this be done?

解决方案

You can make new column in your data frame that contains mean value. I named it as y.int and calculated using function ddply() from library plyr. Here mean value calculated only for the values where Type is Completed (as Requested should be excluded).

library(plyr)
cns<-ddply(cns,.(Name),transform,y.int=mean(Days[Type=="Completed"]))

Now use geom_hline() and new column to add lines to each facet.

plot + geom_hline(aes(yintercept=y.int))

这篇关于将变量geom_hline添加到barplot的所有面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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