datetimechartsstata

Plotting a line using month format


I have a dataset which has a variable month which has the display format %tdMon-YY (such as Jan-2024) and a variable for Exchange rate in integer format. I need to plot a line graph for the two and a vertical line at Mar-2020. I used the following code:

line exchange_rate month, xline("Mar-2020")

This however gives me an error which I suppose is due to typing "Mar-2020" which is not in string format. I have done the same code for a year variable which is an integer and if I did the following then it would run fine.

line exchange_rate year, xline(2020)

I suppose the only problem here is how I'm referring to March 2020, so can anyone please help me understand how you would do this using the correct format (%tdMon-YY).


Solution

  • As the code that worked for year showed, xline() expects numeric argument(s) in the first instance.

    Your date variable is evidently a daily date variable, but you care only about the monthly date part. A quick calculation shows that as a daily date, 1 March 2020 is

    . di mdy(3, 1, 2020)
    21975
    

    and evidently you can get any daily date within March 2020 similarly. So you could use

    xline(21975)
    

    or

    xline(`=mdy(3, 1, 2020)`)
    

    or you could use a convenience function td().

    There are other ways to do it.

    If your daily date variable has e.g. dates such as ..., 1 February 2020, 1 March 2020, 1 April 2020, ... at some point you will find it convenient and even necessary to convert it to a monthly date variable using mofd().

    There is no route to understanding handling dates in Stata that does not run though help datetime.