I'd like to add linking lines for stacked 100% bar chart. As did in the following picture.
Here is part of my ggplot2 code. But I don't know how to make data and use geom_line()/geom_abline()/geom_hline to add linking lines.
pctdata <- mtcars %>%
group_by(am) %>%
count(cyl) %>%
mutate(ratio=n/sum(n))
ggplot(pctdata, aes(x = as.factor(am), y=ratio, fill = as.factor(cyl)))+
geom_bar(position="fill", stat = "identity", width = 0.5) +
geom_text(aes(y=ratio,label=scales::percent(ratio)), position = position_fill(vjust=0.5),color="white") + scale_y_continuous(labels = scales::percent_format())+
coord_flip() +
theme_classic()
Thanks for the tips. I've almost finished it.
Here is my code for reference.
pctdata <- mtcars %>%
group_by(am) %>%
count(cyl) %>%
mutate(ratio=n/sum(n))
linedata = data.frame(x1 = rep(0,4), x2 = rep(1,4),y1 = c(0,0.158, 0.369,1), y2 = c(0, 0.615, 0.846, 1))
ggplot()+
geom_segment(data = linedata, mapping = aes(x = x1 +.25, xend = x2 -0.25, y=y1,yend = y2), linetype = 3) +
geom_bar(pctdata, mapping =aes(x = am, y=ratio, fill = cyl), position=position_fill( reverse = TRUE), stat = "identity", width = 0.5) +
geom_text(pctdata, mapping =aes(x = am, y=ratio, label= scales::percent(ratio)), position = position_fill(vjust=0.5),color="white") +
scale_y_continuous(labels = scales::percent_format()) +
scale_x_continuous(breaks = c(0, 1)) +
labs(x = NULL, y = "Percent (%)") +
coord_flip() +
theme_classic()