以躲避的条形图为中心绘制文本/标签 [英] Plot text/labels centered on a dodged bar plot

查看:33
本文介绍了以躲避的条形图为中心绘制文本/标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在 ggplot2 的条形图中以每个闪避的条为中心显示标签.

I can't figure out how to display labels centered on each dodged bar in a barplot in ggplot2.

我知道我可以使用 position ="dodge" 来避开条形,并且为了使标签在每个条形上居中显示,我需要添加 position = position_dodge(宽度= 1) geom_text() geom_label()命令中.

I know that I can dodge the bars using position = "dodge" and I know that in order for the labels to show up centered on each bar I need to add position = position_dodge(width = 1) in the geom_text() or geom_label() command.

但是由于某种原因它不起作用(请参见下图).我还添加了我的数据和代码.

But for some reason it doesn't work (see Figure below). I also added my data and code.

df <- structure(list(Measure = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1988", 
"2017"), class = "factor"), Province = structure(c(1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 
9L, 10L), .Label = c("BC", "AB", "SK", "MB", "ON", "QC", "NB", 
"PE", "NS", "NL"), class = "factor"), Value = c(363L, 61L, NA, 
69L, NA, NA, 127L, 12L, 92L, 18L, 178L, 29L, 41L, 92L, 284L, 
1019L, 267L, 27L, 77L, 22L)), .Names = c("Measure", "Province", 
"Value"), row.names = 41:60, class = "data.frame")

ggplot(df, aes(x=Province, y=Value)) + geom_bar(aes(fill=Measure), position="dodge", 
stat="identity") + geom_label(aes(label=Value), position = position_dodge(width=1))

推荐答案

我刚刚意识到(由于@aelwan的回答),我唯一要做的就是在 aes()函数,即

I just realized (thanks to @aelwan answer) that the only thing I had to do is adding group=Measure in the aes() function, i.e.

ggplot(df, aes(x=Province, y=Value, group=Measure)) +
       geom_bar(aes(fill=Measure),position="dodge", stat="identity") + 
       geom_label(aes(label=Value),position = position_dodge(width=1))

给出:

这篇关于以躲避的条形图为中心绘制文本/标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆