I am trying to make a mean plot of a variable named "Round" with 95% confidence intervals. Since Ronda's averages are similar, I want to separate the average points and error bars so they don't overlap.
However, I am having a hard time separating the error lines. It seems as if the code doesn't read position_dodge(0.3)
into geom_errorbar
.
Here the code I use:
y <- datos$Ronda
z <- datos$Condicion
g <- datos$Terapia
g = factor(g, levels = c(0,0.1))
z = factor(z, levels = c("High isolation", "Moderate isolation", "Low isolation"))
data <- data.frame(y,z,g)
library(dplyr)
library(ggplot2)
library(tidyverse)
library(scales)
data %>%
group_by(g, z) %>%
summarise(media = mean(y),
desvio = sd(y), #Estimación de la media
error_est = desvio / sqrt(n()), #Error estandar de la estimación de la media.
intervalo_sup = media + (2*error_est), #Techo del intervalo.
intervalo_inf = media - (2*error_est)) %>% #Piso del intervalo al 95%.
#mutate(clave = paste("z",z,"x", x, sep="")) %>% #Genero una clave única para cada combinación de x y z.
ggplot(aes(x = g, y = media, color = z)) +
geom_point() +
#Para que genere una salida gráfica cuando sólo hay un data point.
geom_point(aes(group = z), size=2, position=position_dodge(0.3)) + #Las líneas que unen los puntos de cada grupos xz
geom_errorbar(aes(ymax = intervalo_sup, #Intervalor al 95% para cada punto.
ymin = intervalo_inf),
width=0.1,colour="black",position=position_dodge(0.3)) +
#theme_minimal() +
labs(x = "Terapia", y = "Ronda", color = "Condicion") +
scale_color_manual(labels = c("1", "2","3"), values = c("red", "green","blue")) +
theme(legend.position="bottom", legend.text=element_text(size=12)) +
theme(axis.text=element_text(size=14),
axis.title=element_text(size=14))
Here is the graph I get:
Here is a link to the data .
For it to work you would have to add the argument
group = z
in theaes()
degeom_errorbar
.Your code would look like this:
Why?
Because the
position_dodge
fromgeom_point
responds to the argumentcolor
you defined in the firstaes()
of your function. What it does is move the geometric element horizontally for each group ofz
. However ingeom_errorbar
you are defining a constant color withcolour = "black"
outside ofaes
. That's whyposition_dodge()
it has no effect, it has no defined groups to work on. By defining agroup =
you do something similar to what you get withcolor
(define groups), but these are no longer color dependent.Alternatively you could remove the
colour = "black"
ingeom_errorbar()
and in that case you would have each error bar the same color as the dot and no argument would need to be passedgroup = z
. Depends on your taste, personally I prefer black error bars.Result using
group = z