R条形图-顶部的最高值被隐藏

时间:2018-10-19 15:21:05

标签: r bar-chart

简单的barplot,其值位于小节的顶部(我知道这很愚蠢-我被迫添加它们:)。 text运作良好,但高于最高频率条的值被隐藏。我尝试了边距,但它移动了整个图,而不仅仅是图形区域。你有什么建议?谢谢!

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)

图解示例: enter image description here

2 个答案:

答案 0 :(得分:4)

您可以通过扩展ylim

来解决此问题
bp = barplot(x,names.arg=lbl,main="Ctrl-C clicks",col="grey", ylim=c(0,30)) 

Extended y range

答案 1 :(得分:2)

使用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