I\'m using R and ggplot2 to plot a pretty basic bar graph with error bars, but I\'m having trouble forcing them to be in the center of the bars that I create.
My co
Your bars are 10.8 units wide (12 units each, times 0.9 for the gap), so try:
position = position_dodge(10.8*2)
in your geom_errorbar
call
While @jeremycg's answer is correct (+1 for obscure knowledge of ggplot theme system), it's more of a side-effect than a solution.
Let's just think for a moment of the typical use case scenario for a bar chart. Generally we would use a bar chart when we are trying to present data that are:
Right now, we have data that are:
A dot plot would be more appropriate for this data type. But we can see that it looks a bit ridiculous because our data are not truly continuous.
ggplot(df, aes(Time,CellCount, color = Type)) +
geom_point(stat="identity") +
geom_errorbar(aes(
ymin = CellCount - Error,
ymax = CellCount + Error),
width = 0.9)
For a presentation of this nature, one ought to use a categorical variable for their x-coordinate.
This can be accomplished by pre-processing your variable, Time, as a factor, or by calling the variable as.factor in the aesthetic string (aes
).
ggplot(df, aes(
x=as.factor(Time), # as.factor() makes this a discrete scale
y = CellCount,
fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
geom_errorbar(aes(
ymin = CellCount - Error,
ymax = CellCount + Error),
width = 0.9,
position = position_dodge(width = 0.9)) + # now you can use it
labs(x= "Time (h)", y = "Cell count") +
scale_fill_discrete(labels = c("Anirridia", "Control"))