2

Simple barplot with values on top of bars (I know it is silly - I was forced to add them :)). text works good, but value above highest frequency bar is hidden. I tried margins but it moves the whole plot instead of only the graph area. What can you suggest? Thanks!

x = c(28,1,4,17,2)
lbl = c("1","2","3","4+","tough guys\n(type in)")
bp = barplot(x,names.arg=lbl,main="Ctrl-C clicks",col="grey")
text(x = bp, y = x, label = x, pos = 3, cex = 0.8, col = "red",font=2)

Plot example: enter image description here

Alexey Ferapontov
  • 5,029
  • 4
  • 22
  • 39

2 Answers2

4

You can fix this by extending the ylim

bp = barplot(x,names.arg=lbl,main="Ctrl-C clicks",col="grey", ylim=c(0,30)) 

Extended y range

G5W
  • 36,531
  • 10
  • 47
  • 80
2

Another solution using ggplot2:

library(ggplot2)
x = c(28,1,4,17,2)
lbl = c("1","2","3","4+","tough guys \n(type in)")
test <- data.frame(x, lbl)
bp = ggplot(test, aes(x=lbl, y= x))+
  geom_bar(color = "grey", stat="identity")+ ## set color of bars and use the value of the number in the cells.
  geom_text(aes(label= x), vjust = -1, color = "red")+
  ggtitle("Ctrl-C clicks")+
  theme_bw()+ ## give black and white theme
  theme(plot.title = element_text(hjust = 0.5),## adjust position of title
        panel.grid.minor=element_blank(),  ## suppress minor grid lines
        panel.grid.major=element_blank()  ##suppress major grid lines
        )+
  scale_y_continuous(limits = c(0,30)) ## set scale limits
bp

Ctrl-C clicks

bob1
  • 398
  • 3
  • 12
  • Thanks. This gives me truncated number as well "out-of-the-box". – Alexey Ferapontov Oct 19 '18 at 15:52
  • adjust the `vjust` number - negative for above the box, positive for inside. It's also possible to set the axis limits, like in the solution above. I can add the calls for colors and blank background etc. if you like. – bob1 Oct 19 '18 at 15:58
  • it's already negative, like in your example. I copy-pasted your solution and it gives me "28" cut in half. Cannot attach pic to comments – Alexey Ferapontov Oct 19 '18 at 16:00
  • what happens if you do `vjust = 0` apparently this should sit it on the line according to the justification section here:https://ggplot2.tidyverse.org/articles/ggplot2-specs.html – bob1 Oct 19 '18 at 16:09
  • edited code to add extra customization you can play with if you need. I see that I left `vjust` as `-1`, it should read `-0.2` to match picture. – bob1 Oct 19 '18 at 16:18