Announcement

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

  • Graph with 2 bars, 2 lines and 2 y-axes

    Hello, my data consists of binned observations which contain counts organized by year, engine and costs.

    I am trying to merge two graphs with two axes into one. Here is the code I have used to produce the three graphs below:

    Code:
    graph twoway (bar counts bin_e if engine == 1 & year == 2015, yaxis(1)) ///
    (line cost bin_e if engine == 1 & year == 2015, sort yaxis(2) xline(82 110 160 180, lpattern(dash) lc(gray)))
    Click image for larger version

Name:	statalisthelp1.png
Views:	1
Size:	88.3 KB
ID:	1459452

    Code:
     
    graph twoway (bar counts bin_e if engine == 2 & year == 2015, yaxis(1)) ///
    (line cost bin_e if engine == 2 & year == 2015, sort yaxis(2) xline(82 110 160 180, lpattern(dash) lc(gray)))
    Click image for larger version

Name:	statalisthelp2.png
Views:	1
Size:	87.5 KB
ID:	1459453

    Code:
     
    graph twoway (bar counts bin_e if engine == 1 & year == 2015, yaxis(1)) ///
    (bar counts bin_e if engine == 2 & year == 2015, yaxis (1)) ///
    (line cost bin_e if engine == 1 & year == 2015 , sort yaxis(2) lc(navy) xline(82 110 160 180, lpattern(dash) lc(gray))) ///
    (line cost bin_e if engine == 2 & year == 2015, sort yaxis(2) lc(maroon)), ///
    legend ( ///
    label(1 count a) label(2 count b) label(3 cost a) label(4 cost b))
    Click image for larger version

Name:	statalisthelp3.png
Views:	1
Size:	93.8 KB
ID:	1459454



    The result is close to what I want, but I would like the bars next to each other instead of on top of each other. I have tried combining commands like graph (bar x, over y (asyvars) z) with (twoway line) to no avail. Separately, I get graphs that look like they're getting to the right place, but together it doesn't seem to work. A common error I get is '( bargraph_g invalid name' for code similar to the following:

    Code:
    graph (bar counts if inlist(engine, 1, 2) & year == 2015, over(engine) asyvars over(bin_e)) ///
    (twoway line costs bin_e, sort yaxis(2) xline(82 110 160 180, lpattern(dash))) if engine == 1 & year == 2015
    Additionally, I'd like to ask how I should refer to the two y-axes in the code when changing their titles, labels, ticks, ranges etc.

    Much thanks in advance!
    Last edited by Patrick Zollner; 24 Aug 2018, 02:01.

  • #2
    I played around with it a bit and eventually settled on creating two new variables: bin_e+0.7 and bin_e-0.7 and using those. If you have a more elegant solution I'd still love to hear it.

    Comment

    Working...
    X