1

I have a dataframe of 2 columns, my values and the standard error. What I want is to plot a line with my values and then add the standard error as a shaded area around my line. I do not even know how to start as most of the examples use the geom_ribbon and not an existing column.

I am really confused, is it even possible to plot a shaded area based on an existing column? (any suggestions of tutorials or demos are welcomed!)

foo
  • 33
  • 6
  • 1
    Please supply some sample data and show what you've tried so far. See [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for some details on how to ask a good question – alan ocallaghan Jan 28 '20 at 16:33

2 Answers2

3

you need 3 columns, timestamp, value and std. And it's as simple as use your std column inside the aes(ymin, ymax):

library(tidyverse)
huron <- data.frame(year = 1875:1972, 
                value = LakeHuron,
                std = runif(length(LakeHuron),0,1))

huron %>% 
  ggplot(aes(year, value)) + 
  geom_ribbon(aes(ymin = value - std, ymax = value + std), fill = "steelblue2") + 
  geom_line(color = "firebrick", size = 1)

In case you want to group your data, you should use fill = your_group and group = your_group inside the aes:

library(tidyverse)
huron <- data.frame(year = rep(1875:1972,2), 
                group = c(rep("a",98),rep("b",98)),
                value = c(LakeHuron, LakeHuron + 5),
                std = runif(length(LakeHuron)*2,0,1))

huron %>% 
  ggplot(aes(year, value, fill = group, group=group)) + 
  geom_ribbon(aes(ymin = value - std, ymax = value + std), fill = 
  "steelblue2") + 
  geom_line(color = "firebrick", size = 1)

I posted this tip here: https://typethepipe.com/vizs-and-tips/ggplot_geom_ribbon_shadow/ for more info. Hope it helps!

  • 1
    Thanks Carlos! That worked!Just a question, for cases when we have grouped lines, do we have to add separate geom_ribbons? – foo Jan 28 '20 at 16:45
  • Glad to help! This is a good question, i edited the answer! :) Let me know if it solves your question – Carlos Vecina Tebar Jan 28 '20 at 16:51
  • 1
    Nice post! I focus so much on the analysis of data and so I find myself struggling with the creation of beautiful plots, quite often! Thanks again!. You may also add the inclusion of different linetypes in your post! It works perfectly! – foo Jan 28 '20 at 17:14
1

In this example the se column is your standard errors for the values:

require(tidyverse)
set.seed(42)

n_obs <- 50
my_data <- tibble(
  values = rnorm(n_obs),
  se = rbinom(n_obs, 5, .5)
)


my_data %>%
  ggplot() + 
  geom_line(aes(1:n_obs, values), color = 'red') +
  geom_ribbon(aes(1:n_obs,
                  ymin = values - se,
                  ymax = values + se),
                  alpha = 1/5,
                  fill = 'steelblue')

some line chart with +-1SE

Zlo
  • 1,150
  • 2
  • 18
  • 38