如何在R的barplot中的条上放置值


Answers:


16

要将文本添加到绘图中,只需使用text命令。来自@chl 对上一个问题的回答

##Create data
x = replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)

##Create plot
barplot(matrix(c(5, 3, 8, 9), nr=2), beside=TRUE, 
        col=c("aquamarine3", "coral"), 
        names.arg=LETTERS[1:2], 
        ylim=range(0,12)))

##Add text at coordinates: x=2, y=6
##Use trial and error to place them 
text(2, 6, "A label")
text(5, 10, "Another label")

替代文字


3
我真的不明白为什么将此选项添加到hist()labels=T)中而不是barplot()
chl

7

使用text命令的另一个例子

u <- c(3.2,6.6,11.7,16.3,16.6,15.4,14.6,12.7,11.4,10.2,9.8,9.1,9.1,9.0,8.8,8.4,7.7)
p <-c(3737,3761,3784,3802,3825,3839,3850,3862,3878,3890,3901,3909,3918,3926,3935,3948)
     -c(385,394,401,409,422,430,434,437,437,435,436,437,439,442,447,452)
e <- c(2504,2375,2206,2071,2054,2099,2127,2170,2222,2296,2335,2367,2372,2365,2365,2401)

par(mar=c(2,3,1,2),las=1,mgp=c(2.2,1,0))
x <- barplot(u,names.arg=1990:2006,col="palegreen4",space=.3,ylim=c(0,20),
              ylab="%",xaxs="r",xlim=c(.8,21.6))
text(x,u+.4,format(u,T))
lines(x[-17],100*e/p-55,lwd=2)
points(x[-17],100*e/p-55,lwd=2,cex=1.5,pch=1)
axis(4,seq(0,20,5),seq(55,75,5))
text(c(x[1]+1,x[5],x[16]+1),c(100*e/p-55)[c(1,5,16)]+c(0,-1,0),
      format(c(100*e/p)[c(1,5,16)],T,di=3))
box()

1
(+1)这是艰难的方式:)我喜欢。
chl

3

如果你正在学习到R中的情节你可能看的[R图形库(原来这里)。

那里的所有图形都带有用于构建它们的代码。它是一个很好的资源。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.