R + ggplot : Time series with events

前端 未结 3 616
梦如初夏
梦如初夏 2020-12-22 15:26

I\'m an R/ggplot newbie. I would like to create a geom_line plot of a continuous variable time series and then add a layer composed of events. The continuous variable and it

3条回答
  •  萌比男神i
    2020-12-22 15:41

    Plotly is an easy way to make ggplots interactive. To display events, coerce them into factors which can be displayed as an aesthetic, like color.

    The end result is a plot that you can drag the cursor over. The plots display data of interest:

    Here is the code for making the ggplot:

    # load data    
    data(presidential)
    data(economics)
    
    # events of interest
    events <- presidential[-(1:3),]
    
    # strip year from economics and events data frames
    economics$year = as.numeric(format(economics$date, format = "%Y")) 
    
    # use dplyr to summarise data by year
    #install.packages("dplyr")
    library(dplyr)
    econonomics_mean <- economics %>% 
      group_by(year) %>% 
      summarise(mean_unemployment = mean(unemploy))
    
    # add president terms to summarized data frame as a factor
    president <- c(rep(NA,14), rep("Reagan", 8), rep("Bush", 4), rep("Clinton", 8), rep("Bush", 8), rep("Obama", 7))
    econonomics_mean$president <- president
    
    # create ggplot
    p <- ggplot(data = econonomics_mean, aes(x = year, y = mean_unemployment)) +
      geom_point(aes(color = president)) +
      geom_line(alpha = 1/3)
    

    It only takes one line of code to make the ggplot into a plotly object.

    # make it interactive!
    #install.packages("plotly")
    library(plotly)
    ggplotly(p)
    

提交回复
热议问题