上面的注释栏:

Tyl*_*ker 10 r ggplot2

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

在此输入图像描述

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)) 
Run Code Online (Sandbox Code Playgroud)

Mar*_*ius 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 是的,我刚试过`dodgewidth < - position_dodge(width = 0.9)`,它很好地居中.我不知道为什么0.9会成为神奇数字 (2认同)

San*_*att 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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述