-1
  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()

SiH
  • 1,378
  • 4
  • 18
  • Does this answer your question? [Make the background of a graph different colours in different regions](https://stackoverflow.com/questions/9968975/make-the-background-of-a-graph-different-colours-in-different-regions) – tjebo Nov 22 '21 at 16:09
  • http://idownvotedbecau.se/noresearch/ – tjebo Nov 22 '21 at 16:10
  • yes sir, the question is similar. I want a background based on energy. – SiH Nov 22 '21 at 16:24

3 Answers3

2

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

R_newbie
  • 61
  • 1
1

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

Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22
-1

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()
tdy
  • 36,675
  • 19
  • 86
  • 83
tech2188
  • 1
  • 1