定义R中条形图周围的框的限制

时间:2014-09-04 13:53:13

标签: r plot axis box

我使用以下代码在x轴(0-23)和背景阴影上创建了一个条形图,其中包含24个条形图:

#Data
Hours = seq(from=0, to=23)
Mean = rnorm(24, mean=5, sd=2)

#Create number seq for tick mark locations
at_tick = seq_len(length(Hours)+1) 

#Plot with background rectangle shading
x=barplot(Mean,names.arg=Hours, border="white", ylab="Freq", xlab="Hour", 
          ylim=c(0,10), axes=FALSE, space=0, col="grey50")
X = c(0,5)
Y = c(0,10)
rect(X[1], Y[1], X[2], Y[2], border = "gray80", col = "gray80")
X2 = c(19,24)
Y2 = c(0,10)
rect(X2[1], Y2[1], X2[2], Y2[2], border = "gray80", col = "gray80")
barplot(Mean,names.arg=Hours, ylim=c(0,10), border="white", ylab="", xlab="", axes=FALSE, space=0, col="gray50", add=TRUE) 
axis(2, las=2, pos=0)
axis(1, at = at_tick -1, pos=0, labels = FALSE)

box(which="plot", bty="]") #add a box around the plot

这会创建一个带有周围框的图,该框在两个方向上都超出了x轴的限制。相反,我想在图中添加一个与轴限制对齐的框(即x轴:0-23,y轴:0-10)。我花了很多年的时间试图找到一种方法来做到这一点,没有运气。任何帮助将非常感激。谢谢!

1 个答案:

答案 0 :(得分:2)

如何绘制单独的线条?您可以使用segment功能代替box执行此操作:

segments(24,10, 24,0)
segments(0,10, 24,10)

完整代码:

#Data
Hours = seq(from=0, to=23)
Mean = rnorm(24, mean=5, sd=2)

#Create number seq for tick mark locations
at_tick = seq_len(length(Hours)+1) 

#Plot with background rectangle shading
x=barplot(Mean,names.arg=Hours, border="white", ylab="Freq", xlab="Hour", 
          ylim=c(0,10), axes=FALSE, space=0, col="grey50")
X = c(0,5)
Y = c(0,10)
rect(X[1], Y[1], X[2], Y[2], border = "gray80", col = "gray80")
X2 = c(19,24)
Y2 = c(0,10)
rect(X2[1], Y2[1], X2[2], Y2[2], border = "gray80", col = "gray80")
barplot(Mean,names.arg=Hours, ylim=c(0,10), border="white", ylab="", xlab="", axes=FALSE, space=0, col="gray50", add=TRUE) 
axis(2, las=2, pos=0)
axis(1, at = at_tick -1, pos=0, labels = FALSE)

segments(24,10, 24,0)
segments(0,10, 24,10)

enter image description here