R ggplot2, which reduces the width and distance between the bars

I have read posts and searched for an answer to my problem but cannot find it. Here's the basic idea. I am using ggplot to generate a stacked barcode where each bar is split into groups and the plot is flipped on the horizontal axis. I know how to change the width of the bars using the "width" option, however decreasing the width of the bar leaves a lot of gaps between the columns. Question: how to remove huge amount of white space between columns?

I have put together some reproducible code using the previous question and answer, which has been adapted 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")

      

+2


source to share


1 answer


You can change the aspect ratio of the whole plot with coord_equal

and remove the argument width

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 downside to this approach is that it doesn't work with coord_flip

.

enter image description here

+4


source







All Articles