Reputation: 628
I'm trying to display summary values on my plot for ease of comparison.
Not too sure if I've phrased the question correctly as I haven't found anything other than geom_text
references. I'll try to explain my reasoning below.
Base dataframe with two lines, value vs time.
library(tidyverse)
df <- tibble(
"sample" = as.factor(c(rep("A",6), rep("B",6))),
"time" = c(rep(1:6,2)),
"value1" = c(10,20,30,60,30,30,13,21,32,64,35,32),
"value2" = c(5,15,20,30,20,10,6,15,22,31,42,11)
)
> df
# A tibble: 12 x 4
sample time value1 value2
<fct> <int> <dbl> <dbl>
1 A 1 10 5
2 A 2 20 15
3 A 3 30 20
4 A 4 60 30
5 A 5 30 20
6 A 6 30 10
7 B 1 13 6
8 B 2 21 15
9 B 3 32 22
10 B 4 64 31
11 B 5 35 42
12 B 6 32 11
Calculate the areas between the two lines and join with the original dataframe. (I've joined the summary data due to assuming it would be easier to display on the plots this way, may be incorrect?)
df <- df %>%
group_by(sample) %>%
dplyr::summarise(sum1 = sum(value1),
sum2 = sum(value2),
auc = abs(sum1-sum2)) %>%
dplyr::select(-c(sum1,sum2)) %>%
right_join(df)
> df
# A tibble: 12 x 5
sample auc time value1 value2
<fct> <dbl> <int> <dbl> <dbl>
1 A 80 1 10 5
2 A 80 2 20 15
3 A 80 3 30 20
4 A 80 4 60 30
5 A 80 5 30 20
6 A 80 6 30 10
7 B 70 1 13 6
8 B 70 2 21 15
9 B 70 3 32 22
10 B 70 4 64 31
11 B 70 5 35 42
12 B 70 6 32 11
Plotting the values over time with highlighted area I'm interested in.
I have not been able to figure out how to display the auc
value on the plot. To clarify, I want to extract the values of 70, 80 and display them, for example, on the bottom right of the faceted graphs. (NOT, for example, displaying a value of 80 on every single point on the plot).
Is this possible? I haven't quite found the best way to go about it yet. Appreciate any help.
df %>%
ggplot(aes(x=time,y=value1))+
geom_line()+
geom_line(aes(y=value2),color='red')+
geom_ribbon(aes(ymin = value2, ymax = value1), fill='green', alpha=.3)+
facet_wrap(~sample)
Upvotes: 1
Views: 696
Reputation: 39325
You can do something like this...
df %>%
ggplot(aes(x=time,y=value1))+
geom_line()+
geom_line(aes(y=value2),color='red')+
geom_ribbon(aes(ymin = value2, ymax = value1), fill='green', alpha=.3) +
geom_text(aes(x = 2, y = 60, label = paste0("AUC = ", auc)), color = "red", data = df %>% distinct(sample, auc)) +
facet_wrap(~sample)
...which makes this graph:
Upvotes: 1
Reputation: 183
df %>%
ggplot(aes(x=time,y=value1))+
geom_line()+
geom_line(aes(y=value2),color='red')+
geom_ribbon(aes(ymin = value2, ymax = value1), fill='green', alpha=.3)+
facet_wrap(~sample) +
geom_text(aes(x = 2, y = 60, label = auc))
This gives you what you want I believe. You can relocate the text by changing "2" and "60".
Upvotes: 1