Wednesday, October 3

Frivolous political analysis

Today I wrote a short R function to colour the background of a ggplot with the colour of the governing political party of the day.

Let's start with the frivolous analysis. In government, which political party has better managed employment since the Monthly Labour Force series commenced? Interestingly, since the commencement of the MLFS, both sides of politics have been in control of the economy for a similar period of time.

For US viewers I should explain the colour scheme. In Australia, the right side of politics (the Liberal Party) is coloured blue and the left side (the Labor Party) is coloured red.




The code for the R function follows.

annotateFederalGovernments <- function(plot, xRange)
{
    # ----- safety
    if(is.null(xRange) || length(xRange)!=2) return(plot)

    # ----- build up an history table
    government.history <- data.frame(start=as.Date('1949-12-10'),
        finish=as.Date('1972-12-02'), y1=-Inf, y2=Inf, themer='blue',
        stringsAsFactors=FALSE )
    government.history <- rbind( government.history, 
        data.frame(start=as.Date('1972-12-02'), 
        finish=as.Date('1975-12-13'), y1=-Inf, y2=Inf, themer='red' ) )
    government.history <- rbind( government.history, 
        data.frame(start=as.Date('1975-12-13'), 
        finish=as.Date('1983-03-05'), y1=-Inf, y2=Inf, themer='blue' ) )
    government.history <- rbind( government.history, 
        data.frame(start=as.Date('1983-03-05'), 
        finish=as.Date('1996-03-02'), y1=-Inf, y2=Inf, themer='red' ) )
    government.history <- rbind( government.history, 
        data.frame(start=as.Date('1996-03-02'), 
        finish=as.Date('2007-11-24'), y1=-Inf, y2=Inf, themer='blue' ) )
    government.history <- rbind( government.history, 
        data.frame(start=as.Date('2007-11-24'), 
        finish=as.Date('2100-01-01'), y1=-Inf, y2=Inf, themer='red' ) )

    # ----- triangulate some key facts
    gh <- government.history[ (government.history$finish > xRange[1]), ]
    gh <- gh[ (gh$start < xRange[2]), ]
    if(nrow(gh) == 0)
    {
        print ('Warning annotateFederalGovernments(): date issues')
        return(plot)
    }
    gh[1, 'start'] <- xRange[1]
    gh[nrow(gh), 'finish'] <- xRange[2]

    # ----- add the background to the plot
    plot <- plot + geom_rect( data=gh,
        aes(NULL, NULL, xmin=start, xmax=finish, 
            ymin=y1, ymax=y2, fill=themer), alpha=0.2) +
        scale_fill_manual(values=gh$themer, breaks=gh$themer, 
            guide=FALSE) 
     
    return(plot)
}

No comments:

Post a Comment