How do I force Stata to place a horizontal line above all other charts in the chart?

I am plotting time series and shading specific time periods based on a boolean indicator variable in Stata 13.1 on Windows 7. Time periods are shaded if the indicator variable is 1 and not shaded if not present. I want to draw a horizontal line at a point on the y-axis where the time series is 0. Here's an example using plugin freduse

( ssc install freduse, replace

):

freduse GDPC1 USRECQ, clear
gen qrtr = qofd(daten)
tsset qrtr, q
drop date*

drop if qrtr < tq(1947q1)
replace USRECQ = . if !USRECQ
label var USRECQ "Recession"

gen ly = log(GDPC1)
tsfilter hp lydev = ly, smooth(1600)

#delimit ;
twoway (scatter USRECQ qrtr,
           recast(area)
           bcolor(gs13)
           cmissing(n)
           yaxis(1)
           ylabel(0 1)
           yscale(off))  
       (tsline lydev,
           yaxis(2)
           yscale(alt axis(2))
           ytitle("Deviation from trend", axis(2))),
       yline(0, axis(2))
;
#delimit cr

      

ly_dev

- time series, and USRECQ

- indicator variable. In practice, an indicator variable can be anything, so I don't want to hardcode the values ​​in the shadow in the command twoway

as shown in this Statalist post or plugin nber

in SSC. This code creates this graph:

Incorrect plot

The horizontal line is hidden by the shading because the shader is created first, but the shader needs to be created first, because otherwise it shades the time series plot (since Stata does not support transparency / alpha blending).

Is it possible to force Stata to place this horizontal line on top of all other charts in the chart?

+3


source to share


1 answer


Yes; It can be done. But you must use little force.

Basically, the idea behind yline()

and similar options is to provide baselines that should never be drawn over the data.

So, to subvert that you have to provide your line as data. One way to do this is to simply define a variable that is constant and plot it like a graph line

.

Below is a more general methodology that does not require the added line to be horizontal.

First, for convenience, we calculate the endpoints of the string and put them in local macros. In other examples, this may not be acceptable.



local t1 = tq(1947q1)
local t2 = tq(2014q2) 

      

The key should now start twoway scatteri

, but convert the two dots (in this case) to a string. When we supply two pairs of coordinates, the result is one straight line (which is horizontal). You need a string that corresponds to 0 on the second y-axis:

(scatteri 0 `t1' 0 `t2', recast(line) yaxis(2))  

      

For such tasks, you need to be able to calculate the corresponding coordinates from the data in each case, or return to a constant variable, built as a horizontal line graph.

EDIT: The revised version benefits from Roberto Ferrer's comments.

+3


source







All Articles