简体   繁体   中英

Adding labels over bars in ggplot2

I am using ggplot2 to plot bar chart. I want to add labels over bars in bar chart but the label name of the bar with the highest value gets hidden. I tried to set margin but the label value still not get visible.

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))

And the barplot I get is

在此处输入图片说明

Try using a different value for the expand parameter within 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

情节

或调整限制:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM