如何使用 ggplot2 在 R 中的 geom_bar 上放置标签 [英] How to put labels over geom_bar in R with ggplot2
问题描述
我想在 geom_bar
图表上堆叠一些标签.举个例子:
I'd like to have some labels stacked on top of a geom_bar
graph. Here's an example:
df <- data.frame(x=factor(c(TRUE,TRUE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE)))
ggplot(df) + geom_bar(aes(x,fill=x)) + opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),axis.title.x=theme_blank(),legend.title=theme_blank(),axis.title.y=theme_blank())
现在
表(df$x)
FALSE TRUE
3 5
我想将 3 和 5 放在两个条形的顶部.如果我也可以拥有百分比值,那就更好了.例如.3 (37.5%)
和 5 (62.5%)
.像这样:
(来源:skitch.com)
I'd like to have the 3 and 5 on top of the two bars. Even better if I could have the percent values as well. E.g. 3 (37.5%)
and 5 (62.5%)
. Like so:
(source: skitch.com)
这可能吗?如果是,怎么办?
Is this possible? If so, how?
推荐答案
与 ggplot 中的许多任务一样,一般的策略是将您想要添加到图中的内容放入数据框中,以便变量与情节中的变量和美学相匹配.例如,您将创建一个新的数据框,如下所示:
As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:
dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))
使x
变量与df
中的相应变量相匹配,依此类推.然后你只需使用 geom_text
:
So that the x
variable matches the corresponding variable in df
, and so on. Then you simply include it using geom_text
:
ggplot(df) + geom_bar(aes(x,fill=x)) +
geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
axis.title.x=theme_blank(),legend.title=theme_blank(),
axis.title.y=theme_blank())
此示例将仅绘制百分比,但您也可以通过以下方式将计数粘贴
:
This example will plot just the percentages, but you can paste
together the counts as well via something like this:
dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")
请注意,在当前版本的 ggplot2 中,opts
已弃用,因此我们现在将使用 theme
和 element_blank
.
Note that in the current version of ggplot2, opts
is deprecated, so we would use theme
and element_blank
now.
这篇关于如何使用 ggplot2 在 R 中的 geom_bar 上放置标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!