将geom_text放在闪避的barplot上


96

我试图使标题变得不言自明,但是这里是-数据优先:

dtf <- structure(list(variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 
4L, 4L, 5L, 5L), .Label = c("vma", "vla", "ia", "fma", "fla"), class = "factor"), 
    ustanova = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
    2L), .Label = c("srednja škola", "fakultet"), class = "factor"), 
    `(all)` = c(42.9542857142857, 38.7803203661327, 37.8996138996139, 
    33.7672811059908, 29.591439688716, 26.1890660592255, 27.9557692307692, 
    23.9426605504587, 33.2200772200772, 26.9493087557604)), .Names = c("variable", 
"ustanova", "(all)"), row.names = c(NA, 10L), class = c("cast_df", 
"data.frame"), idvars = c("variable", "ustanova"), rdimnames = list(
    structure(list(variable = structure(c(1L, 1L, 2L, 2L, 3L, 
    3L, 4L, 4L, 5L, 5L), .Label = c("vma", "vla", "ia", "fma", 
    "fla"), class = "factor"), ustanova = structure(c(1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("srednja škola", 
    "fakultet"), class = "factor")), .Names = c("variable", "ustanova"
    ), row.names = c("vma_srednja škola", "vma_fakultet", "vla_srednja škola", 
    "vla_fakultet", "ia_srednja škola", "ia_fakultet", "fma_srednja škola", 
    "fma_fakultet", "fla_srednja škola", "fla_fakultet"), class = "data.frame"), 
    structure(list(value = structure(1L, .Label = "(all)", class = "factor")), .Names = "value", row.names = "(all)", class = "data.frame")))

我想创建一个躲避的条形图,执行操作,coord_flip然后在条形图内放置一些文本标签:

ggplot(bar) + geom_bar(aes(variable, `(all)`, fill = ustanova), position = "dodge") +
 geom_text(aes(variable, `(all)`, label = sprintf("%2.1f", `(all)`)), position = "dodge") +
 coord_flip()

您可以在这里看到输出。

在此处输入图片说明

我认为我要的是琐碎的事情。我希望文本标签“跟随”堆积的条。标签正确地放置在y轴上,但是如何正确地将它们放置在x轴上?


是的...我应该把这个发布在ggplot2邮件列表上。我不想交叉张贴文章,所以我要戴上耐心的帽子,等待@hadley提出一些建议!=)
aL3xa

我错了。而且,显然,我需要更加了解ggplot软件包。
Joris Meys 2011年

Answers:


152

这是你想要的吗?

ggplot(bar) + 
  geom_bar(aes(variable, `(all)`, fill = ustanova), position = "dodge") +
  geom_text(aes(variable, `(all)`, label = sprintf("%2.1f", `(all)`)), 
            position = position_dodge(width = 1)) + 
  coord_flip()

关键是使用position = position_dodge(width = 1)而不是position = "dodge",这只是一个没有任何参数的快捷方式。

在此处输入图片说明


ggplot2_2.0.0你发现几个例子?geom_text就如何位置geom_text上回避或堆叠杆(评为“代码块# Aligning labels and bars")。在Q&A 什么是position_dodge宽度参数?提供的话题的更详细说明。


1
正是我想要的!我欠你一杯啤酒!=)
aL3xa

2
因此,没有办法使它自动化吗?必须始终指定宽度吗?
vashts85 '16

12
这只有在我添加fill = ustanovageom_text图层之后才对我有用,特别是当您有许多水平条(每x可能只需要3个以上的条)并且文本的中断次数必须与条相同时。
艾伦(Alan)

3
对于多面和闪避,这是一个有用的答案:stackoverflow.com/a/26661791/1000343
Tyler Rinker '17

在我对stackoverflow进行的所有搜索中,@ Alan中,您的答案是唯一解决我的问题的答案。
Ga13
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.