Search code examples
rplotggvis

Making a Background for a Line Plot with Ribbon Plot


[Edited Title and crossed off questions that were secondary to the main question]

What I want is a simple line plot with points (easy) with a background created by a data frame of tier levels (hard for me)

Example for what I am trying to recreate example plot CODE

# libraries used  
library(dplyr)  
library(ggvis)  
library(magrittr)  

# create example data frame
months <- c("oct", "nov", "dec", "jan", "feb", "march", "april", "may",
"june")
#months <- 1:9
tier3low <- (rep(150, 9))
tier3high <- c(157, 158, 162, 162, 166, 167, 169, 172, 172)
tier2high <- c(164, 166, 170, 171, 176, 178, 180, 182, 182)
tier1high <- rep(185, 9)
tier_range <- seq(from = 150, to = 185, by = 4)
scores <- c(156, 163, 162, 172, 173, 174, 175, 177, 183)
df <- data.frame(months, tier3low , tier3high, tier2high, tier1high,
tier_range, scores)
# make levels
levels(df$months) <- c("oct", "nov", "dec", "jan", "feb", "march", "april",
"may", "june")

# what I have tried
df %>%
  group_by(months) %>% 
  ggvis(x = ~months, y = ~tier_range) %>%
  layer_ribbons(y = ~tier3low,  y2 = ~tier3high, stroke := "red") %>% 
  layer_ribbons(y = ~tier3high, y2 = ~tier2high, stroke := "yellow") %>% 
  layer_ribbons(y = ~tier2high, y2 = ~tier1high, stroke := "green") %>% 
  layer_lines(y   = ~scores) %>% 
  layer_points(y  = ~scores)   

Which produces this
enter image description here

Edited out these questions as per requests from comment 1. The plots are not filling in with each other 2. The actual line are not printed on the plot 3. The data has been rearranged and in the wrong months

MAIN QUESTION

The plot isn't filling between each other and I don't understand why this isn't the correct solution. What in your opinion would be a better way to accomplish this.


Solution

  • You actually weren't far away. There's three things you needed to fix:

    You need to use fill, not stroke, to determine the color of the ribbons

    The data frame needs to be sorted by month, as the ribbon draws from left to right

    You had a surplus definition of y in your first call to ggvis, which I think confused things as you had to define y separately again in each layer (probably didn't do you harm but certainly confused me).

    Here's what I think you need:

    df %>%
       arrange(months) %>%
       ggvis(x = ~months) %>%
       layer_ribbons(y = ~tier3low,  y2 = ~tier3high, fill := "red") %>% 
       layer_ribbons(y = ~tier3high, y2 = ~tier2high, fill := "yellow") %>% 
       layer_ribbons(y = ~tier2high, y2 = ~tier1high, fill := "green") %>% 
       layer_lines(y   = ~scores) %>% 
       layer_points(y  = ~scores)   
    

    enter image description here