2016-09-25 66 views
0

我试图将文本打印限制为条形图中的一个变量。我该如何标签粉色栏601, 215, 399, 456在ggplot2中仅显示一个文本值

ggplot(df, aes(Var1, value, label=value, fill=Var2)) + 
    geom_bar(stat="identity", position=position_dodge(width=0.9)) + 
    geom_text(position=position_dodge(width=0.9)) 

enter image description here

structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 
            4L, 1L, 2L, 3L, 4L), .Label = c("Zero", "1-30", "31-100", "101+" 
           ), class = "factor"), Var2 = structure(c(1L, 1L, 1L, 1L, 2L, 
                      2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("Searches", "Contact", 
                                "Accepts"), class = "factor"), value = c(21567, 215, 399, 456, 
                                          13638, 99, 205, 171, 5806, 41, 88, 78)), .Names = c("Var1", "Var2", 
                                                       "value"), row.names = c(NA, -12L), class = "data.frame") 

回答

2

您可以在geom_text一个ifelse语句做到这一点。首先,从主ggplot2调用中删除label=value。然后,在geom_text中,在label上添加ifelse条件,如下所示。另外,如果您要避开一种以上的审美,您可以通过创建一个闪避对象来节省一些打字。

pd = position_dodge(0.9) 

ggplot(df, aes(Var1, value, fill=Var2)) + 
    geom_bar(stat="identity", position=pd) + 
    geom_text(position=pd, aes(label=ifelse(Var2=="Searches", value,""))) 

如果你想在酒吧中间的文本,而不是在顶部,你可以这样做:

geom_text(position=pd, aes(label=ifelse(Var2=="Searches", value, ""), y=0.5*value)) 

实际上,你可以保持label声明(与ifelse条件加)在主ggplot调用,但由于label只适用于geom_text(或geom_label),我通常保持与geom而不是主要通话。