在ggplot2中的条形图上添加标签

时间:2016-02-02 14:51:38

标签: r ggplot2

我正在使用ggplot2绘制条形图。我想在条形图中的条形图上添加标签,但隐藏了具有最高值的条形图的标签名称。我试图设置保证金,但标签值仍然不可见。

library(ggplot2)
x <- c(1:27)
y <- c(988,1195,804,574,414,309,234,196,169,125,95,73,57, 63 ,31,32 ,28 ,29 ,37 ,37 ,21 ,20 ,5,4,2,1,4)
z <- c(11233,7856,5926,4615,3714, 3037, 2548, 2156, 1842, 1610, 1436, 1302, 1177,1066  ,1000 ,936,882,828,760,697,659,621,611,603,599,597,591)
dat <- data.frame(x,y,z)

g <- ggplot(dd, aes(x = dat$x, y = dat$y)) + 
  geom_bar(stat = "identity", colour = "black", fill = "pink", width = .5,
           position = position_dodge()) + 
  geom_text(aes(label = dat$z, hjust = 0), position = position_dodge(width = 0.9), 
            angle = 90)
g
g + theme_bw() + 
  theme(panel.grid.major = element_blank(),
        panel.background = element_blank(),
        plot.margin=unit(c(0.5, 1, 1, 2), "lines")) + 
  scale_y_continuous(expand = c(0, 0))

我得到的条形图是

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试为expand中的scale_y_continuous参数使用不同的值:

g <- ggplot(dat, aes(x = x, y = y)) + 
  geom_bar(stat = "identity", colour = "black", fill="pink", width = .5, 
           position = position_dodge()) +
  geom_text(aes(label = z, hjust=0), 
            position = position_dodge(width = 0.9), angle = 90) +
  scale_y_continuous(expand = c(0.15, 0))
g

Plot

答案 1 :(得分:1)

或调整限制:

+ scale_y_continuous(expand = c(0,0), limits = c(0, max(y) * 1.15))