rpickmans
rpickmans

Reputation: 103

Bar and line graphs overlaying on same figure, containing groups, and by another group

I am attempting to create a figure that essentially has a bar graph corresponding to one group and a line graph for another group, but where there are two groups within each of the formerly described groups. I have tried various ways of using twoway and binscatter but have not been able to achieve what I would like.

I am including a picture of what I would like to create:

enter image description here

(On the y-axis is "cost" which both the line graphs and bar graphs refer to. From a data visualization standpoint I would personally use either 4 line graphs or even 4 bar graphs, but 2 lines, and 2 sets of bars are what is desired).

I imagine it might take some reshaping, but it might not. If anyone has any leads, I would definitely appreciate it. If color could be left to the user's desire, that would be even better. Although I think the data is shaped so that one could create the graph "automatically" by referring to the categories, it might be possible to reshape the data and use county-year as the categorical variable.

The code to develop the dataset (thanks to Nick Cox for developing a superior version of my example code):

clear
set seed 1234 
set obs 16
g year = cond(_n > 8, 2010, 2000) 
bysort year: g country = cond(_n > 4, "China", "USA")  
bysort year country : gen month = _n 
g cost = runiform(0, 100)

Upvotes: 0

Views: 813

Answers (1)

Lu Han
Lu Han

Reputation: 310

I seem to understand what you wanted to create. See the example code below:

//Trick 1
separate cost,by(year)

//Trick 2
gen month1 = month - 0.12
gen month2 = month + 0.12

twoway (bar cost2000 month1 if country == "USA", barw(0.2) color(red)) || ///
(bar cost2010 month2 if country == "USA", barw(0.2)  color(ltblue))  || ///
(line cost2000 month if country == "China",lcolor(cranberry) lwidth(0.8) ) || ///
(line cost2010 month if country == "China",lcolor(blue) lwidth(0.8)), ///
legend(order(1 "2000" "USA" 2 "2010" "USA" 3 "2000" "CHN" 4 "2010" "CHN") row(1)) ///
ytitle("Cost")

The resulting graph looks like: enter image description here

Here are the two tricks that you can find from Nick Cox's previous posts: Trick 1; Trick 2.

Upvotes: 3

Related Questions