上面的注释栏:

时间:2012-04-26 04:30:23

标签: r ggplot2

ggplot中的躲避条形图再次令我难过。几个星期前,我在这里询问了关于栏上方文字的注释(LINK)并得到了使用+ stat_bin(geom="text", aes(label=..count.., vjust=-1))的极好回复。我想,既然我已经有了计数,我会在..之前和之后提供它们,我告诉stat_bin positiondodge。它将它们排列在组的中心上方并进行上下调整。可能是次要的。请帮我把文字翻到栏上。

enter image description here

mtcars2 <- data.frame(type=factor(mtcars$cyl), 
    group=factor(mtcars$gear))
library(plyr); library(ggplot)
dat <- rbind(ddply(mtcars2,.(type,group), summarise,
    count = length(group)),c(8,4,NA))

p2 <- ggplot(dat,aes(x = type,y = count,fill = group)) + 
    geom_bar(colour = "black",position = "dodge",stat = "identity") +
    stat_bin(geom="text", aes(position='dodge', label=count, vjust=-.6)) 

2 个答案:

答案 0 :(得分:12)

我无法将位置闪避排队,所以我最终创建了一个position_dodge对象(这是正确的术语吗?),将其保存到变量,然后将其用作两个geoms的位置。 有点令人愤怒的是,他们似乎仍然偏离中心。

dodgewidth <- position_dodge(width=0.9)
ggplot(dat,aes(x = type,y = count, fill = group)) + 
  geom_bar(colour = "black", position = dodgewidth ,stat = "identity") +
  stat_bin(geom="text", position= dodgewidth, aes(x=type, label=count), vjust=-1)

enter image description here

答案 1 :(得分:9)

已更新 geom_bar()需要stat = "identity"

我认为这也是你想要的。

mtcars2 <- data.frame(type = factor(mtcars$cyl), group = factor(mtcars$gear))
library(plyr); library(ggplot2)
dat <- rbind(ddply(mtcars2, .(type, group), summarise, count = length(group)), c(8, 4, NA))

p2 <- ggplot(dat, aes(x = type,y = count,fill = group)) + 
  geom_bar(stat = "identity", colour = "black",position = "dodge", width = 0.8) +
  ylim(0, 14) +
  geom_text(aes(label = count, x = type, y = count), position = position_dodge(width = 0.8), vjust = -0.6)
p2

enter image description here