更改ggplot中的布局

时间:2018-08-28 10:04:44

标签: r ggplot2

我遇到了另一个关于ggplot条形图的小问题:

temp<-tribble(
 ~kt, ~absent, ~`absent, represented`, ~`absent, not represented`,
 "Berne", 97.5, 2.5, 0,
 "Basel", 97.1, 1, 1.9,
 "Zurich", 99.2, 0.8, 0,
 "Geneva", 93.8, 3.9, 2.3
)

temp2 <- gather(temp, ` `, val, -kt)
temp2$` `<-temp2$` ` %>% fct_relevel('absent','absent, represented', 'absent, not represented')
temp2[,2] <- as.factor(temp2[[2]])
temp2[,2] <- factor(temp2$` `, levels = rev(levels(temp2$` `)))

ggplot(temp2, aes(kt, val, fill = ` `)) +   geom_col(color='black', position='dodge') +
  theme_bw()+
  labs(x='City', y='Percentage') + scale_fill_grey(start = 0.5, end = .9)+
scale_y_continuous()+
 geom_text(aes(label=val), position=position_dodge(width=0.9), hjust=-0.3, vjust=.4, size=3)+
 guides(fill=guide_legend(title='Label', reverse=T))+
 coord_cartesian(ylim = c(0, 100))+
 coord_flip(ylim=c(0, 100))

我的问题是,上方的数字被裁剪了,我不知道如何扩大数字与绘图边框之间的间距。我当然可以扩大轴的比例(例如,从0%扩大到120%),但这不是我想要的。有没有人有办法解决吗?谢谢!

1 个答案:

答案 0 :(得分:1)

正如许多评论者所建议的那样,您可以稍微扩展y轴或移动标签。完全不同的方法是禁用面板上的“剪切”,因此p是ggplot对象:

g <- ggplotGrob(p)
> g
TableGrob (12 x 11) "layout": 19 grobs
    z         cells       name                                            grob
1   0 ( 1-12, 1-11) background               rect[plot.background..rect.32871]
2   5 ( 6- 6, 4- 4)     spacer                                  zeroGrob[NULL]
3   7 ( 7- 7, 4- 4)     axis-l           absoluteGrob[GRID.absoluteGrob.32832]
4   3 ( 8- 8, 4- 4)     spacer                                  zeroGrob[NULL]
5   6 ( 6- 6, 5- 5)     axis-t                                  zeroGrob[NULL]
6   1 ( 7- 7, 5- 5)      panel                      gTree[panel-1.gTree.32818]
7   9 ( 8- 8, 5- 5)     axis-b           absoluteGrob[GRID.absoluteGrob.32825]
8   4 ( 6- 6, 6- 6)     spacer                                  zeroGrob[NULL]
9   8 ( 7- 7, 6- 6)     axis-r                                  zeroGrob[NULL]
10  2 ( 8- 8, 6- 6)     spacer                                  zeroGrob[NULL]
11 10 ( 5- 5, 5- 5)     xlab-t                                  zeroGrob[NULL]
12 11 ( 9- 9, 5- 5)     xlab-b titleGrob[axis.title.x.bottom..titleGrob.32838]
13 12 ( 7- 7, 3- 3)     ylab-l   titleGrob[axis.title.y.left..titleGrob.32835]
14 13 ( 7- 7, 7- 7)     ylab-r                                  zeroGrob[NULL]
15 14 ( 7- 7, 9- 9)  guide-box                               gtable[guide-box]
16 15 ( 4- 4, 5- 5)   subtitle         zeroGrob[plot.subtitle..zeroGrob.32867]
17 16 ( 3- 3, 5- 5)      title            zeroGrob[plot.title..zeroGrob.32866]
18 17 (10-10, 5- 5)    caption          zeroGrob[plot.caption..zeroGrob.32869]
19 18 ( 2- 2, 2- 2)        tag              zeroGrob[plot.tag..zeroGrob.32868]
> i <- which(g$layout$name == 'panel')
> g$layout$clip[i] <- 'off'
> library(grid)
> grid.draw(g)

此方法的唯一缺点是面板边框在面板及其内容的顶部 上绘制。