Bar graph in ggplot2 with width as a variable and even spacing between bars

后端 未结 2 944
执笔经年
执笔经年 2021-01-02 03:41

So I am trying to make a stacked bar graph with bar width mapped to a variable; but I want the spacing between my bars to be constant.

Does anyone know how to make t

相关标签:
2条回答
  • 2021-01-02 03:58

    For a categorical or "discrete" scale - you can adjust the width, but it needs to be between 0 and 1. Your value.x's put it over 1, hence the overlap. You can use rescale, from the scales packages to adjust this quickly so that the within category width of the bar is representative of some other variable (in this case value.x)

    install.packages("scales")
    library(scales) 
    ggplot(dd,aes(x=variable,y=value.y,fill=Date)) +
    geom_bar(aes(width=rescale(value.x,c(0.5,1))),stat="identity",position="stack")' +
    coord_flip()
    

    Play with rescaling for optimal "view" change 0.5 to 0.25... etc.

    enter image description here

    Personally, I think something like this is more informative:

    ggplot(dd,aes(x=variable,y=value.y,fill=Date)) +
    geom_bar(aes(width=rescale(value.x,c(0.2,1))),stat="identity") +
    coord_flip() + facet_grid(~Date) + opts(legend.position="none")
    

    enter image description here

    0 讨论(0)
  • 2021-01-02 04:21

    Attempt # 2.

    I'm tricking ggplot2 into writing a continuous scale as categorical.

    # The numbers for tmp I calculated by hand. Not sure how to program 
    # this part but the math is 
    # last + half(previous_width) + half(current_width)
    # Change the 1st number in cumsum to adjust the between category width
    

    tmp <- c(2.91,7.02,14.715,27.75,38.22,46.47,57.845,77.19,101.235) + cumsum(rep(5,9))

    dd$x.pos1 <- rep(tmp,each=5)
    ggplot(dd,aes(x=x.pos1,y=value.y,fill=Date)) +
    geom_bar(aes(width=value.x),stat="identity",position="stack") + 
    scale_x_continuous(breaks=tmp,labels=levels(dd$variable)) + 
    coord_flip()
    

    enter image description here

    For good measure you're probably going to want to adjust the text size. That's done with ... + opts(axis.text.y=theme_text(size=12))

    0 讨论(0)
提交回复
热议问题