barplot背后的情节线

时间:2012-11-28 03:55:31

标签: r plot

我想创建一个条形图,其中条形图绘制在水平线的顶部。

以下代码可以实现此目的:

y <- c(1,2,3,5)
barplot(y)
abline(h=mean(y))
barplot(y, add=T)

但是,我担心add=T中的barplot()参数,如果重复使用,会引入打印工件。我很好奇是否有上述代码的替代品(尽管上面的代码可能是最快的方法)。

2 个答案:

答案 0 :(得分:11)

你可以在第一次电话中没有任何内容:

y <- c(1,2,3,5)
barplot(rep(NA,length(y)),ylim=c(min(0,y),max(y)),axes=FALSE)
abline(h=mean(y))
barplot(y, add=T)

enter image description here

答案 1 :(得分:7)

如果你使用ggplot2,你不必担心这个。你的问题归结为geom顺序:

ggplot(data.frame(x=1:4, y=y), aes(x=x, y=y)) + 
    geom_bar(stat="identity") + 
    geom_hline(yintercept=mean(y), color="red")

line in front

相比之下:

ggplot(data.frame(x=1:4, y=y), aes(x=x, y=y)) + 
    geom_hline(yintercept=mean(y), color="red") +
    geom_bar(stat="identity")

line behind

相关问题