I have read a similar post on SO, but was not able to adapt the answer to my specific case. I am working with time series data and would like to combine two different data sets into the same plot. Although I could combine the data into one dataframe, I am really interested in understanding how to reference multiple datasets.
Mock Data:
require(ggvis)
dfa <- data.frame(
date_a = seq(from= as.Date("2015-06-10"),
to= as.Date("2015-07-01"), by= 1),
val_a = c(2585.150, 2482.200, 3780.186, 3619.601,
0.000, 0.000, 3509.734, 3020.405,
3271.897, 3019.003, 3172.084, 0.000,
0.000, 3319.927, 2673.428, 3331.382,
3886.957, 2859.887, 0.000, 0.000,
2781.443, 2847.377) )
dfb <- data.frame(
date_b = seq(from= as.Date("2015-07-02"),
to= as.Date("2015-07-15"), by= 1),
val_b = c(3250.75429, 3505.43477, 3208.69141,
-2.08175, -27.30244, 3324.62348,
2820.91075, 3250.75429, 3505.43477,
3208.69141, -2.08175, -27.30244,
3324.62348, 2820.91075) )
Using the data provided above, I am able to create separate plots with the code below:
Separate Plots: (Works)
dfa %>%
ggvis( x= ~date_a , y= ~val_a, stroke := "black", opacity := 0.5 ) %>%
scale_datetime("x", nice = "month", domain = c(as.Date("2015-06-10"),
as.Date("2015-07-15") )) %>%
layer_lines() %>% layer_points( fill := "black" )
dfb %>%
ggvis( x= ~date_b , y= ~val_b, stroke := "red", opacity := 0.5 ) %>%
scale_datetime("x", nice = "month", domain = c(as.Date("2015-06-10"),
as.Date("2015-07-15") )) %>%
layer_lines() %>% layer_points( fill := "red" )
The desired output is these two lines (black and red) to be on the same plot. Here are a couple of unsuccessful attempts:
Attempt #1 adapted from SO post:
ggvis( data = dfa, x = ~date_a, y = ~val_a) %>% layer_lines(stroke := "black", opacity := 0.5 ) %>%
layer_lines( data = dfb, x= ~date_b , y= ~val_b, stroke := "red",
opacity := 0.5 ) %>%
scale_datetime("x", nice = "month", domain = c(as.Date("2015-06-10"),
as.Date("2015-07-15") ))
## Error in new_prop.default(x, property, scale, offset, mult, env, event, :
## Unknown input to prop: c(16618, 16619, 16620, 16621, 16622, 16623, 16624, ...
Attempt #2 based on RStudio documentation:
ggvis( data = NULL, x = ~date_a, y = ~val_a) %>%
layer_lines(stroke := "black", opacity := 0.5, data = dfa ) %>%
layer_lines( x= ~date_b , y= ~val_b, stroke := "red",
opacity := 0.5, data = dfb ) %>%
scale_datetime("x", nice = "month", domain = c(as.Date("2015-06-10"),
as.Date("2015-07-15") ))
## Error in func() : attempt to apply non-function
Here is a minimalistic implementation in ggplot2:
require(ggplot2)
ggplot() +
geom_line(data = dfa, aes(x = date_a, y = val_a ), colour = "black") +
geom_line(data = dfb, aes(x = date_b, y = val_b ), colour = "red")
Again, a working solution and brief explanation would be greatly appreciated. Thank you in advance for the help.