In ggplot2 I\'m attempting a simple thing that I just can\'t get for some reason. I have adjusted means and SE in a data frame and want to plot the means, error bars and th
As an alternative to mnel's answer, you could create a new variable, so that you have a column where all 3 groups have the same value:
data1$all <- "All"
And then use that as the group
aesthetic for your line:
ggplot(data1, aes(x=group, y=estimate)) +
geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE),
colour="black", width=.1, position=pd) +
geom_line(aes(x=group, y=estimate, group=all)) +
geom_point(position=pd, size=4)
Mnel's answer is probably more elegant, but this might work better if the groups aren't numbers and can't be converted to numeric so straightforwardly.
If you remove the grouping by group
within the ggplot call and set x = as.numeric(group )
within the call to geom_line
, the it works.
Also, you don't need to re-reference data1
within geom_line
ggplot(data1, aes(x=group, y=estimate)) +
geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE),
colour="black", width=.1, position=pd) +
geom_line( aes(x=as.numeric(group), y=estimate)) +
geom_point(position=pd, size=4)
If you group
by group
, then you only have one value for geom_line
to create a line from, hence the error message. The same error occurs if ggplot
is considering the x
or y
mapping variables as a factor - this is because if you code a variable as a factor R (and ggplot) will consider them independent groups, and not connect the points - this is sensible default behaiviour.
This will work with alphabetic factor labels due to the way factors are coded internally by R
(ie as.numeric(factor) returns numbers not the factor labels)
ie.e
Changing group to a
, b
, c
levels(data1[['group']]) <- letters[1:3]
ggplot(data1, aes(x=group, y=estimate)) +
geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE),
colour="black", width=.1, position=pd) +
geom_line( aes(x=as.numeric(group), y=estimate)) +
geom_point(position=pd, size=4)
You might also look at the 2nd answer to this SO Question If you are working toward a fuller implementation this might save you some time.