henryTi
henryTi

Reputation: 131

What should I do to add the text to the right place in the bar chart?

enter image description hereIn a basic bar plot, I want to add text in a right place but my text overlap with the standard error bar. Here are my code and output. Thank you.

d<-data.frame(Proband=c(1400,1500), 
          Sibling=c( 1700,1800), 
          Proband2=c( 1200, 1250), 
          Sibling2=c(  1300,  1500))

d <- do.call(rbind, d)
colnames(d) <- c("A","B")


Se<-data.frame(Proband=c(   100,450    ), 
               Sibling=c(    170, 180 ), 
               Proband2=c(120,125 ),
               Sibling2=c(130,150 ))

Se <- do.call(rbind, Se)

colnames(Se) <- c("A","B"))


freq<- c(21,26,32,56,45,66,78,88)

mycolors2<-c(paste0("royalblue", c(4:3)), c("steelblue4", "steelblue3"))

barCenters<-barplot(d, beside = TRUE, ylim=c(0,5000), legend.text = rownames(d), 
                    args.legend = list(x = "topleft", bty="n"), 
                    col=mycolors2, xlab="[![enter image description here][1]][1]Size (kb)",
                    ylab="Average ")


arrows(barCenters, d - Se * 2, barCenters,
       d + Se * 2, lwd = 1.5, angle = 90,
       code = 3, length = 0.05)


text(barCenters, d +  Se * 2 , freq ,cex=1,srt = 90)

Upvotes: 1

Views: 106

Answers (2)

jay.sf
jay.sf

Reputation: 72901

Since y=d + Se*2 are the height of your upper error bars, you may want to add a small extension to it. E.g. adding + 300 to x looks nice. You also could add argument adj=-.5 to that.

text(barCenters, d + Se*2 + 300, freq, cex=1, srt=90)

enter image description here

However, probably the numbers are somewhat misleading at this position and could be confused with just these errors. I suggest to place the number of cases (?) directly into the bars.

text(barCenters, 350, freq, cex=.9, col="white")

enter image description here

You might also want to consider explaining the numbers in the description or ?legend.

Upvotes: 1

andrew_reece
andrew_reece

Reputation: 21274

The y value you are setting in text() is very small, compared to the range displayed on the axis. Just increase the multiplier on Se and the labels will appear above the error bars.

text(barCenters, d +  Se * 5 , freq ,cex=1,srt = 90)

enter image description here

Note: You may want to adjust the spacing formula for your labels, because it currently depends on the magnitude of your standard errors. This means that bars with large errors will place labels higher on the plot.

Upvotes: 1

Related Questions