Utilizando el siguiente código dibujo una serie de líneas y de intervalos de confidencia del 95% usando geom_line
y geom_ribbon
.
Me gustaría suavizar el trazado de la línea de medias y de los sombreados de los intervalos de confidencia. He intentado utilizar geom_smooth
, pero no consigo el ajuste deseado.
library(dplyr)
library(ggplot2)
library(scales)
tribble( ~y, ~z, ~g,
1 ,"A", 1,
2 ,"A", 1,
2 ,"B", 1,
3 ,"B", 1,
1.5 ,"C", 1,
2 ,"C", 1,
2 ,"D", 1,
2 ,"D", 1,
3 ,"A", 2,
3.5 ,"A", 2,
0.5 ,"B", 2,
2 ,"B", 2,
2 ,"C", 2,
2 ,"C", 2,
1.5 ,"D", 2,
1 ,"D", 2,
4 ,"A", 3,
3.5 ,"A", 3,
5.5 ,"B", 3,
3 ,"B", 3,
3.3 ,"C", 3,
2.1 ,"C", 3,
1.3 ,"D", 3,
1.2 ,"D", 3)-> data
z = factor(z, levels = c("A", "B", "C", "D"))
data %>%
group_by(g, z) %>%
summarise(media = mean(y),
desvio = sd(y),
error_est = desvio / sqrt(n()),
intervalo_sup = media + (2*error_est),
intervalo_inf = media - (2*error_est)) %>%
ggplot(aes(x = g, y = media, color = z)) +
geom_line(aes(group = z, color = z), size=0.5) +
geom_ribbon(aes(x = as.numeric(g), ymax = intervalo_sup,
ymin = intervalo_inf,
fill = z),
alpha=0.3, colour = NA) +
labs(x = "X", y = "Y", fill = "Condition", color = "Condition") +
scale_fill_manual(labels = c("A", "B", "C", "D"), values = c("blue","green","red", "black")) +
scale_color_manual(labels = c("A", "B", "C", "D"), values = c("blue","green","red", "black")) +
scale_x_discrete(breaks = seq(1, 3, by = 1)) +
theme(legend.position="bottom", legend.text=element_text(size=12)) +
theme(axis.text=element_text(size=14),
axis.title=element_text(size=14))
geom_smooth()
es un método que te puede ayudar, revisa esto: - https://eliocamp.github.io/codigo-r/2018/06/tu-propio-geom-smooth/ - https://plot.ly/ggplot2/smooth/ - https://www.youtube.com/watch?v=hxk2cgdChUw