Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Irregular gaps between bars on graph bar

    Dear Statalisters

    I ran into a strange problem when making a bar graph. I have a lot of categories over which the graph is plotted, which seems to be causing problems with the spacing of graphs, so they don't line up with labels. Here is a reproducible example using the auto.dta dataset:

    Code:
    sysuse auto, clear
    graph bar price, over(foreign) asyvars over(make, sort(price) des label(angle(90))) legend(pos(6) col(4)) ytitle("Price") scale(0.5)
    This produces the following graph:
    Graph.gph

    As you see, the labels under the graphs do not line up. It is unclear which bar belongs to which label. Here's what I've tried to no avail:
    • Use hbar instead of bar -- same issue
    • Change the scale
    • Played around with bargap
    Is there anything I am doing wrong or is this just a bug? Any hints appreciated.
    Attached Files

  • #2
    The problem lies in the nature of the data. You are trying the graph two bars (domestic and foreign) for each type of car. But by construction, every type of car is either domestic or foreign, but not both. Therefore you will only get one bar per type of car. If it's domestic, you get a blue bar towards the left of the label, for foreign cars you get a red bar towards the right side of the label.

    If you are interested in the difference in price between foreign and domestic cars, here are two alternatives:
    Code:
    sysuse auto, clear
    * Alternative 1
    graph bar price, over(make, sort(price) des label(angle(90))) over(foreign) legend(pos(6) col(4)) ytitle("Price") scale(0.5) nofill
    * Alternative 2
    separate price, by(foreign)
    graph bar price0 price1, over(make, sort(price) des label(angle(90))) legend(pos(6) col(4)) ytitle("Price") scale(0.5) ///
    nofill yvaroptions(relabel(1 "Domestic"  2"Foreign"))
    Last edited by Wouter Wakker; 23 Jul 2019, 05:57.

    Comment


    • #3
      Wouter Wakker gives an excellent answer, which can be tweaked.

      Code:
      separate price, by(foreign) veryshortlabel
      is undocumented but designed for problems like these. See also https://www.stata-journal.com/sjpdf....iclenum=gr0023

      Comment


      • #4
        Thank you very much, both, that was exactly what I needed. Wouter, thanks for the excellent explanation for why my approach didn't work.

        Comment

        Working...
        X