Search code examples
rcsvxtsdygraphs

R dygraphs - plot certain content of columns


I have a csv file "fruit.csv" looking like that:

"Date","Fruit","Count"
2019-01-01,Apple,3
2019-01-01,Pear,5
2019-01-01,Banana,4
2019-02-01,Apple,4
2019-02-01,Pear,4
2019-02-01,Banana,6
...

I want to plot the data having the date in the x-axis and the number in the y-axis. Especially, i want the graph to only show the data of a certain fruit, e.g. only apples. This is what I have until now, plotting all fruits at once:

data <- read.csv("Path/to/fruit.csv")

data$Date <- as.Date(data$Date)

time_series <- xts(data$Count, order.by = data$Date)
dygraph(time_series)

What do I need to add, to specify the fruit I want to plot?


Solution

  • Here are some approaches:

    First, use dplyr to filter() the data ahead of time:

    library(dplyr)
    apples <- data %>%
      filter(Fruit == "Apple")
    apples_ts <- xts(apples$Count, order.by = apples$Date)
    dygraph(apples_ts)
    

    Second, subset the data in a more traditional way ahead of time.

    apples <- data[which(data$Fruit == "Apples"),]
    apples_ts <- xts(apples$Count, order.by = apples$Date)
    dygraph(apples_ts)
    

    Third, subset the data in the call to xts:

    apples_ts <- xts(data[data$Fruit == "Apple",]$Count, 
                     order.by = data[data$Fruit == "Apple",]$Date)
    dygraph(apples_ts)
    

    Fourth, write a custom function so you don't need to repeat this code for each fruit:

    fruit_dygraph <- function(data, fruit) {
      fruit_ts <- xts(data[data$Fruit == fruit,]$Count, 
                     order.by = data[data$Fruit == fruit,]$Date)
      dygraph(fruit_ts)
      }
    fruit_dygraph(data, fruit = "Apple")