DeltaIV
DeltaIV

Reputation: 5646

Draw "error bars" for multiple categories

I have a data frame with (min,max) values for different categories, for example:

    case1     case2
 1 0.8945 0.8943867
 2 0.8950 0.8952849

I would like to make a plot where, for each category, only a vertical segment with short horizontal segments at the bottom and at the top is drawn: it looks like an error bar, but it doesn't have a central point. If necessary, I can live with the central point, though. Each segment must be labeled with the corresponding category name, as the boxes of a boxplot:

boxplot(df,cex.axis=1.5)

enter image description here

But the look of the bars must be that of functions such as plotCI, segments, etc.:

require(plotrix)
x=0:1
plotCI(x,apply(df,2,mean),li=df[1,],ui=df[2,],xlab="categories",ylab="values")

enter image description here

This looks fine, but the x-axis is numerical, while I need category names on the x-axis. Also, I don't like the bars to be so far away from each other, and so close to the plot margins. Is it possible to put them closer to the center, as for the boxes of a boxplot?

Upvotes: 0

Views: 251

Answers (1)

Pop
Pop

Reputation: 12411

You have at least two possibilities:

  • Without ggplot2:

    require(plotrix)
    plotCI(apply(df,2,mean),li=df[1,],ui=df[2,],xlab="categories",ylab="values")
    axis(side = 1, at = c(1,2), labels = c("case1", "case2"))
    

enter image description here

  • With ggplot2:

First redefine your data.frame:

df2 = data.frame(vmin =  c(0.8945, 0.8943867), vmax=c(0.8950, 0.8952849), case=c("case1", "case2"))

Then, use geom_errorbar

library(ggplot2)
p <- ggplot(df2, aes(ymin = vmin, ymax = vmax, x = case))
p + geom_errorbar()

enter image description here

Upvotes: 2

Related Questions