Reputation: 11
I'm looking a way to build in ggplot a graph like this:
I've build horizontal bars with percentage, but i don't know how to make error bars crossing
Now my plot is like this:
Thanks everyone
Upvotes: 0
Views: 90
Reputation: 174278
You didn't provide a reproducible example, so I have no idea how your data is laid out. I have had to guess to try to recreate your data and your plot:
library(ggplot2)
df <- data.frame(Domanda = rep(c("Utile", "Totale", "Intuitiva", "Interessante",
"Chiara", "Bella"), each = 2),
voto = factor(rep(c("[1-3]", "[4-6]"), 6),
levels = c("[4-6]", "[1-3]")),
`Popolazioni_relativa` = c(13, 87, 15, 85, 25, 75, 8,
92, 30, 70, 30, 70)/100,
CI_95_lower = c(4, 4, 6, 6, 14, 14, 2, 2, 16, 16, 16, 16)/100,
CI_95_upper = c(20, 20, 25, 25, 35, 35, 16, 16, 40, 40, 40, 40)/100)
ggplot(df, aes(Domanda, `Popolazioni_relativa`, fill = voto)) +
geom_col() +
coord_flip() +
geom_errorbar(aes(ymin = CI_95_lower, ymax = CI_95_lower), position = "identity") +
geom_errorbar(aes(ymin = CI_95_upper, ymax = CI_95_upper), position = "identity") +
labs(y = "Popolazio relativa")
There is no geom in ggplot2 to do what you want, so you have to do it yourself with polygons:
errordf <- data.frame(x = rev(do.call(c, lapply(0:5, `+`, c(.56, .8, 1, 1, 1.2, 1.45)))),
y = c(13, 4, 13, 13, 20, 13,
15, 6, 15, 15, 25, 15,
25, 14, 25, 25, 35, 25,
8, 2, 8, 8, 16, 8,
30, 16, 30, 30, 40, 30,
30, 16, 30, 30, 40, 30)/100,
voto = factor(rep(rep(c("[4-6]", "[1-3]"), each = 3), 6),
levels = c("[4-6]", "[1-3]")),
groups = rep(1:12, each = 3))
ggplot(df, aes(Domanda, `Popolazioni_relativa`, fill = voto)) +
geom_col() +
coord_flip() +
labs(y = "Popolazio relativa") +
geom_polygon(data = errordf, aes(x, y, group = groups), position = "identity") +
scale_fill_manual(values = c("#D03020", "#3060C0"))
Created on 2020-06-13 by the reprex package (v0.3.0)
Upvotes: 1