0
test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
    var2 = 250 + c(0, cumsum(runif(49, -10, 10)))
  )

Given the above test data, I would like to do the following:

(1) plot the lines similar to this: Plotting two variables as lines using ggplot2 on the same graph

(2) add an overall confidence band for these lines (lines can be seen as points), similar to this: Find points over and under the confidence interval when using geom_stat / geom_smooth in ggplot2

I know how to do them separately but not sure how to combine them in a single plot.

yliueagle
  • 1,191
  • 1
  • 7
  • 22
  • 3
    Take the "general approach" [as in this answer to plotting multiple lines](https://stackoverflow.com/a/3777592/903061), then add `geom_smooth` with the color aesthetic set to NULL. – Gregor Thomas Feb 26 '19 at 13:45
  • 1
    Please add the code you've used for the separate plots to your question. – erc Feb 26 '19 at 13:49

1 Answers1

0

From this post you can check one of the answers were geom_ribbon is used instead of geom_line. This should answer (2). With respect to (1), it could be plotted the same way as you said in the link you mentioned.

Lets assume that you want to keep var0 in the x axis, and plot with respect to var1 and var2.

To do this you have to first gather var1 and var2

test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
    var2 = 250 + c(0, cumsum(runif(49, -10, 10)))
  ) %>%
  gather(key="var",value="value",var1:var2)

This yields as follows:

> head(test_data)
       var0  var    value
1 100.00000 var1 150.0000
2  85.67636 var1 146.4407
3  76.86862 var1 151.6061
4  79.46151 var1 143.6943
5  96.86709 var1 147.8999
6  91.20310 var1 157.2294

Now, to plot accordingly, you'd have to plot by the new group variable "var" (contanining names of groups "var1" and "var2"), plotting a ribbon geom_ribbon for upper and lower bounds, and a geom_linecall for plotting the actual line.

test_data %>%
  ggplot(aes(x=var0,y=value,group=var)) +
  geom_ribbon(aes(ymin=value*0.95,ymax=value*1.05),fill="grey70") +
  geom_line()

This yields:

Plot

Just Burfi
  • 159
  • 9