I'm trying to add a connecting line in my plot, something like this (this is done having the statics already calculated and directly plotted):
mydata <- structure(list(`Rango edad` = structure(c(3L, 3L, 3L, 4L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("18-30",
"31-55", "56-70", ">70"), class = "factor"), value = c(8.25,
3.26, 1.07, 2.16, 3.25, 2.63, 3.66, 2.12, 1.83, 4.04, 0.36, 5.74,
1.45, 1.73, 1.76, 3.25, 2.2, 2.45, 0.8, 1.5, 0.5, 0.54, 3.45,
1.34, 3.97, 0.43, 1.52, 2.14, 1.55, 2.45, 0.58, 1.2, 0.46, 5.9,
1.08, 1.28)), row.names = c(NA, 36L), class = "data.frame")
dfma <- aggregate(value ~ `Rango edad`, mydata, FUN = mean)
dfma$up <- dfma$value + (aggregate(value ~ `Rango edad` , dfm, FUN = mad)$value)
dfma$low <- dfma$value - (aggregate(value ~ `Rango edad` , dfm, FUN = mad)$value)
ggplot(dfma, aes(`Rango edad`, value,color = `Rango edad`)) +
geom_line(aes(group = 1), color = "black") + geom_point(size = 5) +
geom_errorbar(aes(ymax = up, ymin = low), width = .25)
When I calculate those statistics through stat_summary
, the connecting line goes crazy...
ggplot(mydata, aes(`Rango edad`, value, color = `Rango edad`)) +
geom_line(aes(group = 1)) +
stat_summary(aes(`Rango edad`, value), geom ="point", show.legend = F, fun = mean, size = 5) +
stat_summary(aes(`Rango edad`, value), geom ="linerange", show.legend = F, fun = mean,
fun.min = function(y) mean(y) - sd(y), fun.max = function(y) mean(y) + sd(y))
... I know the problem is in aes(group = ...)
but I cannot fix it in any way. Any idea? Thanks!
You only want to connect the dots, not everything else, so it works if you use a method similar to the way you plot these dots:
ggplot(mydata, aes(`Rango edad`, value, color = `Rango edad`)) +
stat_summary(aes(group = 1), geom = "line", show.legend = F, fun = mean, color = "black") +
stat_summary(aes(`Rango edad`, value), geom ="point", show.legend = F, fun = mean, size = 5) +
stat_summary(aes(`Rango edad`, value), geom ="linerange", show.legend = F, fun = mean,
fun.min = function(y) mean(y) - sd(y), fun.max = function(y) mean(y) + sd(y))