I am trying to make a line and point graph with errorbars. It has different factors, however some factors have only one value. I found out that if i use position_dodge, one of the single value factor has a much wider error bar compared to the other error bars in the graphs. Somehow position_dodge has an influence on the width on the error bar. I did not found anyone that had the same problem before so I hope that someone can help me.
The dummy data:
require(ggplot2)
x <- c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,3,3,5)
y <- c(3,5,6,3,5,3,5,6,2,6,3,7,3,6,2,1,5,8,7)
se <- x*0.2
treatment <- c("A", "B","C", "D","A", "B","C", "D","A", "B","C", "D","A", "B","C", "D","E", "F", "G" )
data <- data.frame(x, y, se ,treatment)
data$treatment <- as.factor(data$treatment)
First a plot without position_dodge - everything is fine
# Without position dodge
myplot <- ggplot(data, aes(x=x, y=y, group= treatment, fill = treatment, colour = treatment)) +
geom_line(stat="identity", size = 1) +
geom_point(stat="identity", size = 3, shape = 21) +
geom_errorbar(aes(ymin = y-se, ymax = y+se), width = 0.2)
myplot
Now a plot with position dodge:
# With position dodge
myplot <- ggplot(data, aes(x=x, y=y, group= treatment, fill = treatment, colour = treatment)) +
geom_line(stat="identity", size = 1, position=position_dodge(width=0.2)) +
geom_point(stat="identity", size = 3, shape = 21, position=position_dodge(width=0.2)) +
geom_errorbar(aes(ymin = y-se, ymax = y+se), width = 0.2, position=position_dodge(width=0.2))
myplot
As you can see the error bar on the far right has a much larger width compared to the other error bars. This is probably because there are no overlapping x variables for this point, and than the error bars can have a normal size. I still would like to know how I can get the error bars to have the same width.
x=1
will be for 4 points,x = c(1, 1.02, 1.04, 1.06)
, then remove dodge option. – zx8754