在 ggplot2 中只显示一个文本值

Pie*_*une 2 r ggplot2

我试图将文本打印限制为条形图中的一个变量。我怎么能只标记粉红色条601, 215, 399, 456

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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")
Run Code Online (Sandbox Code Playgroud)

eip*_*i10 6

你可以用一个做到这一点ifelse的说法geom_text。首先,label=value从主 ggplot2 调用中删除。然后,在如下图上geom_text添加ifelse条件label。此外,如果您要躲避多种美学,则可以通过创建躲避对象来节省一些打字时间。

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,"")))
Run Code Online (Sandbox Code Playgroud)

如果您希望文本位于栏的中间而不是顶部,您可以执行以下操作:

geom_text(position=pd, aes(label=ifelse(Var2=="Searches", value, ""), y=0.5*value))
Run Code Online (Sandbox Code Playgroud)

您实际上可以将label语句(ifelse添加了条件)保留在主 ggplot 调用中,但由于label仅适用于geom_text(or geom_label),因此我通常将其保留在 geom 而不是主调用中。