在ggplot2中仅显示一个文本值

在ggplot2中仅显示一个文本值

本文介绍了在ggplot2中仅显示一个文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本打印限制为条形图中的一个变量.我怎样才能给粉色条标记 601、215、399、456 ?

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)) +
  geom_text(position=position_dodge(width=0.9))
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")

推荐答案

您可以使用 geom_text 中的 ifelse 语句执行此操作.首先,从主ggplot2调用中删除 label = value .然后,在 geom_text 中的 label 上添加一个 ifelse 条件,如下所示.另外,如果您要避开一种美学,则可以通过创建避开对象来节省键入内容.

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

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

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.

这篇关于在ggplot2中仅显示一个文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:59