Pierre Lafortune Pierre Lafortune - 1 year ago 110
R Question

Show only one text value in ggplot2

I'm attempting to limit the text printing to one variable in a bar plot. How can I just label the pink bar

601, 215, 399, 456

ggplot(df, aes(Var1, value, label=value, fill=Var2)) +
geom_bar(stat="identity", 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")

Answer Source

You can do this with an ifelse statement in geom_text. First, remove label=value from the main ggplot2 call. Then, in geom_text add an ifelse condition on the label as shown below. Also, if you're dodging more than one aesthetic, you can save some typing by creating a dodging object.

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,"")))

If you want the text in the middle of the bar, rather than at the top, you can do:

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

You can actually keep the label statement (with the ifelse condition added) in the main ggplot call, but since label only applies to geom_text (or geom_label), I usually keep it with the geom rather than the main call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download