In Stata, how can I combine box plots of different

2019-08-15 08:47发布

问题:

I'm trying to combine several box plots across categories of different size. Here is an example illustrating problem:

sysuse auto

graph box mpg, by(rep78, rows(1)) name(g1, replace )
graph box mpg, by(foreign, rows(1)) name(g2, replace )

graph combine g1 g2 , ycom r(2)

This gives me the following results.

All works according to the manual so for but I have two problems with this output. Firstly - aesthetics. Personally, I think plot with the same width across rows would look better.

Secondly, and more importantly - on more complex graphs the font size for categories, axes, etc. is also sized proportionally. So even if I specify, let's say - medium size of axis label on all graphs - some of them will be slightly bigger or smaller.

I was wondering if there is an option to programmatically force width of second row of box plots to have the same size as the first one.

回答1:

Is this you want? It is based on a trick, but the trick is quite general.

sysuse auto, clear
expand 2
gen what = cond(_n <= 74, rep78, 6 + foreign)
label def what 6 Domestic 7 Foreign
label val what what
graph box mpg, by(what, note("Repair record and Foreign") row(2) holes(8 9 10))

The logic is that

  1. The two categorical variables are combined lengthwise. That ensures that each box plot will be the same size.

  2. By specifying holes, we persuade graph box to put graphs on two rows.

I guess that your label size problem will disappear once 1 is solved.

For even more flexibility, you may need to abandon graph box and use twoway instead. A detailed discussion was given by me in the Stata Journal in 2009: you can go straight to http://www.stata-journal.com/sjpdf.html?articlenum=gr0039