Home > Software design >  geom_rect to show variation of a categorical variable in the background of line plot
geom_rect to show variation of a categorical variable in the background of line plot

Time:11-23

  1. Below is an example of output vs time.
  2. I have used duration to color the line.
  3. I also want to include energy level in plot. How can I use rectangle panel (geom_rect) in the plot background.
library(tidyverse)

tbl <- tibble(time = 1:100,
              output = - time^2   5*time,
              duration = c(rep("start", 30), rep("mid", 40), rep("end", 30)),
              energy = c(rep("high", 40), rep("medium", 30), rep("low", 30)))


ggplot(data = tbl,
       aes(x = time,
           y = output,
            color = duration))   
  geom_line()   
  theme_bw()

CodePudding user response:

I used data.table to create the helper table energy, I am pretty sure if you prefer another method you can convert it easily.

setDT(tbl)
library(data.table)

energy <- tbl[, .(first = first(time), last = last(time)), by  = energy]

ggplot(data = tbl)  
  geom_line(aes(x = time, y = output, color = duration), size = 2)  
  geom_rect(data = energy, aes(NULL, NULL, xmin = first, xmax = last, fill = energy), ymin = -Inf, ymax = Inf, alpha = 0.3)

This creates the graph below enter image description here

CodePudding user response:

I can't comment, but if you wanna the dplyr version, one option is

energy= tbl %>% group_by(energy) %>% mutate(first= first(time), last=last(time)) %>% 
  select(energy, first, last) %>% distinct()

but I like the data.table version

CodePudding user response:

You should be able to add it as another layer if you override the y value. Add transparency by adding alpha = (% transparent).

ggplot(data = tbl, aes(x = time, y = output, color = duration))   
  geom_line()  
  geom_rect(y= anothery, alpha = 0.5)  
  theme_bw()
  • Related