Help with plotting shift in results of a test over time
Hi,
I need some help with plotting shift in results of a test over time.
I will try to keep details to the necessary minimum. I have little to no flexibiity with type of chart, as the community is somewhat fixated to this visualisation
library(tidyverse)
sample_data <- tibble(
res = factor(c(0:6)),
time_1 = sample(0:20, 7, replace = T),
time_2 = sample(0:20, 7, replace = T)
) %>% pivot_longer(cols = c(time_1, time_2))
sample_data %>%
ggplot(aes(value, name, fill = res))+
geom_bar(stat = "identity")
I would like to connect the edges of the groups with lines, to highlight the change in categories over time. I am hoping to reach this end result.
My question is, how to plot the connecting lines?
Thanks
Edit:
found the solution:
library(tidyverse)
sample_data <- tibble(
res = c(0:6),
time_1 = sample(0:20, 7, replace = T),
time_2 = sample(0:20, 7, replace = T)
) %>% pivot_longer(cols = c(time_1, time_2))
bar_plot <- sample_data %>%
ggplot(aes(value, name, fill = res))+
geom_bar(stat = "identity", width = 0.6) # set width to get exact y and yend coordinates below.
for (i in min(sample_data$res):max(sample_data$res) ){
bar_plot <- bar_plot + geom_segment(aes(
x = sample_data %>% filter(res<= !!i & name == "time_1") %>% pull(value) %>% sum(),
xend = sample_data %>% filter(res<= !!i & name == "time_2") %>% pull(value) %>% sum(),
y = 1.3 ,
yend = 2 - 0.3
))
}
bar_plot
The solution was in unquoting the i variable using bang-bang (!!) for the aes() to work, which quotes ist arguments.
https://ggplot2.tidyverse.org/reference/aes.html
Posted Sep 24, 2021, 5:37 AM UTC · edited
Maybe a sankey diagram might help