ggplot2 条形图,geom 底部和 x 轴之间没有空间,上方留有空间 [英] ggplot2 bar plot, no space between bottom of geom and x axis keep space above

查看:23
本文介绍了ggplot2 条形图,geom 底部和 x 轴之间没有空间,上方留有空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 ggplot2 中绘制条形图时,我想将条形底部和 x 轴之间的空间减少到 0,但保持条形和绘图框上方的空间.我有一个技巧可以在下面做到这一点.它很脏,我想再次干净.有没有办法在没有肮脏的小黑客的情况下实现这种行为?

When I plot a bar graph in ggplot2 I would like to reduce the space between the bottom of the bars and the x-axis to 0, yet keep the space above the bars and the plot box. I have a hack to do it below. It's dirty and I want to be clean again. Is there a way to achieve this behavior without the dirty little hack?

默认(希望在条形上方留有空间,但不希望在条形下方留有空间):

ggplot(mtcars, aes(x=as.factor(carb))) + 
    geom_bar()

使用展开(不希望的上方有 0 个空格,但在条形下方有 0 个空格):

ggplot(mtcars, aes(x=as.factor(carb))) + 
    geom_bar() + 
    scale_y_continuous(expand = c(0,0)) 

Dirty Hack(我喜欢它,但它......好吧,肮脏):

ggplot(mtcars, aes(x=as.factor(carb))) + 
    geom_bar() + 
    scale_y_continuous(expand = c(0,0)) +
    geom_text(aes(x=1, y=10.3, label="Stretch it"), vjust=-1)

推荐答案

R 文档包括一个名为 expansion 的新便利函数,用于将 expand 参数作为 expand_scale()ggplot2 v3.3.0 发布.

The R documentation includes a new convenience function called expansion for the expand argument as the expand_scale() became deprecated as of ggplot2 v3.3.0 release.

ggplot(mtcars) +
  geom_bar(aes(x = factor(carb))) + 
  scale_y_continuous(expand = expansion(mult = c(0, .1)))

这篇关于ggplot2 条形图,geom 底部和 x 轴之间没有空间,上方留有空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆