FiofanS - 1 year ago 61
R Question

# How to show standard deviation as a shape?

I have the following data frame

`df`
:

``````structure(list(queue = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("XXX1",
"XXX2", "XXX3", "XXX4",
"XXX5", "XXX6", "XXX7",
"XXX8", "XXX9", "XXX10"), class = "factor"),
hour = c(8, 9, 10, 11, 12, 13), num_at = c(5, 10.6923076923077,
8.35294117647059, 7.74285714285714, 10.0769230769231, 9.34615384615385
), num_wt = c(1.8, 8.28571428571429, 11.3478260869565, 11.2121212121212,
17.5185185185185, 6.68421052631579),num_wt_se = c(0.8, 0.25, 1.3, 1.4,
1.5, 2.6),num_at_se = c(1.2, 1.2, 1.3, 1.2,
1.1, 2.3)), .Names = c("queue",
"hour", "num_at", "num_wt","num_at_se","num_wt_se"), row.names = c(NA, 6L), class = "data.frame")
``````

I created a chart with two line curves, the 1st corresponds to
`num_wt`
, while the 2nd corresponds to
`num_at`
values.

``````library("dplyr")
library("tidyr")
library("ggplot2")

p <- df[df\$queue == "XXX1",] %>%
gather(key, num, num_wt, num_at) %>%
ggplot(aes(x=hour, y=num, colour=key)) +
geom_smooth(span = 0.3) +
scale_color_manual(labels = c("Line 1", "Line 2"), values = c("#F8AA5A", "#BD63BD")) +
labs(title = "Title",
x = "Hour",
y = "Value",
color = "")
p
``````

Now I want to show the standard deviation for
`num_wt`
and
`num_at`
that is stored in
`num_wt_se`
and
`num_at_se`
, correspondingly. I would like to depict the standard deviation as a shape, not as lines. How can I do it?
I googled for a possible solution and found this one, however it shows nothing in my case:

`stat_smooth(method="loess", span=0.1, se=TRUE, aes(fill=key), alpha=0.3) +`

assuming your dataset is called d and you don't `gather()`, how about this

``````ggplot(d, aes(x=hour, y=num_at)) +
geom_ribbon(aes(ymax = num_at + num_at_se,
ymin = num_at - num_at_se),
fill = grey(0.5), alpha = 0.5) +
geom_line()
``````

if you want to maintain the `gather()` step then try this

``````dd <- d %>%
gather(variable, value, -(1:2)) %>%
separate(variable, c("type", "measurement"), "t") %>%