R ggplot2 reducing bar width and spacing between b

2019-07-16 21:30发布

问题:

I've been reading posts and searching for an answer to my problem but can't find one. Here's the basic idea. I'm using ggplot to produce a stacked barchart where each bar is broken down by group and the plot is flipped on the horizontal axis. I know how to change the width of the bars using the "width" option, however reducing the bar width leaves a lot of white space between the bars. Question: how do I remove the huge amounts of space between the bars?

I've cobbled together some reproducible code using a previous question & answer that has been tailored to my needs. Any help would be appreciated!

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")

回答1:

You could change the aspect ratio of the whole plot using coord_equal and remove the width argument from geom_bar.

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

The drawback of this approach is that it does not work with coord_flip.



标签: r ggplot2