fedpug
fedpug

Reputation: 15

How to iterate plot over different variables?

I have the following code:

hist house1 if house1 >0 & house1 <200000, bin(25) fraction by(Year) 

graph export house1.png, replace

I would like to iterate it substituting house1 with car1 and bed1 without copy-pasting the code and substituting, or at least something like:

var = "house1"

hist var if house1 >0 & house1 <200000, bin(25) fraction by(Year) 

graph export var.png, replace

So that I can change just the value assigned to var.

Upvotes: 1

Views: 58

Answers (1)

user8682794
user8682794

Reputation:

A simple foreach loop will work:

foreach x in house1 car1 bed1 {
    display "hist `x' if `x' >0 & `x' <200000, bin(25) fraction by(Year)"
    display "graph export `x'.png, replace"
}

hist house1 if house1 >0 & house1 <200000, bin(25)fraction by(Year)
graph export house1.png, replace
hist car1 if car1 >0 & car1 <200000, bin(25)fraction by(Year)
graph export car1.png, replace
hist bed1 if bed1 >0 & bed1 <200000, bin(25)fraction by(Year)
graph export bed1.png, replace

Here x is a local macro that gets the values specified in foreach.

Note that the display command is used for illustration and is not necessary.

Upvotes: 2

Related Questions