【问题标题】:R ggplot2 reducing bar width and spacing between barsR ggplot2减少条形宽度和条形之间的间距
【发布时间】:2012-12-13 21:39:25
【问题描述】:

我一直在阅读帖子并寻找问题的答案,但找不到。这是基本的想法。我正在使用 ggplot 生成一个堆叠条形图,其中每个条形图按组细分,并且该图在水平轴上翻转。我知道如何使用“宽度”选项更改条的宽度,但是减小条的宽度会在条之间留下大量空白。问题:如何消除条之间的巨大空间?

我使用以前根据我的需要量身定制的问题和答案拼凑了一些可重现的代码。任何帮助将不胜感激!

df <- structure(list(A = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L), .Label = c("0-50,000", "50,001-250,000", "250,001-Over"), class = "factor"),
    B = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0-50,000",
    "50,001-250,000", "250,001-Over"), class = "factor"), Freq = c(0.507713884992987,
    0.258064516129032, 0.23422159887798, 0.168539325842697, 0.525280898876405,
    0.306179775280899, 0.160958904109589, 0.243150684931507,
    0.595890410958904)), .Names = c("A", "B", "Freq"), class = "data.frame", row.names = c(NA,
-9L))

library(ggplot2)

bp <- ggplot(data=df, aes(x=A, y=Freq))+
    geom_bar(width=0.2,stat="identity",position="fill") + 
    theme_bw() + 
    theme(axis.title.y=element_blank()) +
    theme(axis.text.y=element_text(size=10)) +
    theme(axis.title.x=element_blank()) +
    theme(legend.text=element_text(size=10)) +
    theme(legend.title=element_text(size=10)) +
    scale_y_continuous(labels = percent_format()) 
  bp + geom_bar(colour="white",width=0.2,stat="identity",position="fill",show_guide=FALSE) + coord_flip() +theme(panel.grid.minor=element_blank(), panel.grid.major=element_blank())+ theme(legend.position="bottom")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用coord_equal 更改整个绘图的纵横比,并从geom_bar 中删除width 参数。

    library(ggplot2)
    library(scales)
    
    ggplot(data=df, aes(x=A, y=Freq)) +
        geom_bar(stat="identity",position="fill") + 
        theme_bw() + 
        theme(axis.title.y=element_blank()) +
        theme(axis.text.y=element_text(size=10)) +
        theme(axis.title.x=element_blank()) +
        theme(legend.text=element_text(size=10)) +
        theme(legend.title=element_text(size=10)) +
        scale_y_continuous(labels = percent_format()) +
        geom_bar(colour="white",stat="identity",position="fill",show_guide=FALSE) + 
        theme(panel.grid.minor=element_blank(), panel.grid.major=element_blank()) + 
        theme(legend.position="bottom") +
        coord_equal(1/0.2)   # the new command
    

    这种方法的缺点是它不适用于coord_flip

    【讨论】:

    • 感谢您抽出宝贵时间回复我。在这种情况下,能够沿水平轴绘制图表非常重要:(但是解决方案的其余部分本身工作得很好,我刚刚了解了 coord_equal :) 再次感谢!