ggplot2:如果position =" fill"在barplot上添加标签

时间:2016-05-25 15:49:50

标签: r ggplot2 label geom-bar

我想在已填充的条形图上添加%-figures。这是标签位于错误位置的情节:

enter image description here

以下是数据框:

x0 <- expand.grid(grp    = c("G1","G2")
                 , treat = c("T1","T2")
                 , out   = c("out1","out2","out3","out4")
)
set.seed(1234)
x0$n <- round(runif(16,0,1)*100,0)
head(x0)
  grp treat  out  n
1  G1    T1 out1 11
2  G2    T1 out1 62
3  G1    T2 out1 61
4  G2    T2 out1 62
5  G1    T1 out2 86
6  G2    T1 out2 64

现在,我将grp / treat中的总和添加到数据帧中(使用sql,抱歉!):

x0 <- sqldf(paste("SELECT a.*, (SELECT SUM(n)"
                  ,"            FROM x0 b"
                  ,"            WHERE a.grp = b.grp"
                  ,"                  AND a.treat = b.treat"
                  ,"           ) tot"
                  ," FROM x0 a"
                  ," ORDER BY a.grp,a.treat,a.out"
                  )
            )
x0$p <- with(x0, n/tot)
x0$p2 <- with(x0, paste(formatC(p*100, digits=2
              , format="fg"),"%",sep=""))
head(x0)
  grp treat  out  n tot          p    p2
1  G1    T1 out1 11 192 0.05729167  5.7%
2  G1    T1 out2 86 192 0.44791667   45%
3  G1    T1 out3 67 192 0.34895833   35%
4  G1    T1 out4 28 192 0.14583333   15%
5  G1    T2 out1 61 160 0.38125000   38%
6  G1    T2 out2  1 160 0.00625000 0.62%

以下是我如何获得情节:

ggplot(x0, aes(grp, weight=n)) +
         geom_bar(aes(fill = out), position = "fill") +
         facet_grid(.~treat) +
         scale_y_continuous(labels=percent) +
         geom_text(aes(label=p2, y=p))

我可以使用累积百分比向数据框添加新变量,但我想知道是否有更简单的方法来添加标签。

1 个答案:

答案 0 :(得分:3)

为避免自行创建排名值,您可以在position = "stack" geom_text中使用fill。正如您在注释中所述,数据集必须按ggplot(x0, aes(grp, weight = n)) + geom_bar(aes(fill = out), position = "fill") + facet_grid(.~treat) + scale_y_continuous(labels=percent) + geom_text(aes(label = p2, y=p), position = "stack") 变量排序,以便以正确的顺序获取堆栈以匹配条形堆栈。

geom_text(aes(label = ifelse(p < .05, NA, p2), y = p), position = "stack")

this question

您可能最终需要删除一定尺寸以下的标签,以消除上图中看到的重叠。像<form id="registerForm" name="registerForm" ng-submit="createUser($event)"> <label for="email">Email</label> <input type="text" id="email" name="email" ng-model-options="{ updateOn: 'blur' }" ng-model="register.email" required> <div ng-messages="registerForm.email.$error" ng-Show="registerForm.email.$dirty && registerForm.email.$invalid"> <div class="form-error is-visible" ng-message="required">required</div> <div class="form-error is-visible" ng-message="alreadyTaken">Email already in use. <a href="/recover-password">Do you want to recover the password?</a></div> </div> </form> 之类的东西会删除非常小的值的标签。