如何使用mtext在分组条形图的条上添加值?

时间:2012-08-11 02:53:11

标签: r plot

如何使用mtext在条形图上写入值?

# Grouped Bar Plot
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",xlab="Number of Gears", col=c("darkblue","red"),legend = rownames(counts), beside=TRUE, horiz=TRUE)

mtext(counts )   # But position is not at each bar. 

如何在每个条形图上添加相应的值?

1 个答案:

答案 0 :(得分:19)

嗯,mtext通常用于边距。您是否有理由不想使用text

 bplt <- barplot(counts, 
                 main="Car Distribution by Gears and VS", xlab="Number of Gears", 
                 col=c("darkblue","red"), legend = rownames(counts), 
                 beside=TRUE, horiz=TRUE)

# variable 'bplt' is now a matrix of vertical bar positions on the y-axis

text(x= counts+0.3, y= bplt, labels=as.character(counts), xpd=TRUE)
# Needed to use xpd=TRUE because the xlimits were too narrow.

enter image description here