在条形图中添加两条垂直线

时间:2015-11-20 15:51:20

标签: r lattice

我正在尝试在我制作的条形图上添加两条垂直线,但遇到了麻烦。

示例数据集

data<-data.frame(area=rep(c("ES","OC","VB"),each=2,times=2),num=c(0,10,23,40,25,60,80,45,10,25,10,0),
    bin=rep(c(85,90),times=3))

条形码代码。大多数格式化代码用于实际数据集。

require(lattice)         
barchart(num~as.factor(bin), data=data,col=c("black","lightslategray","light gray"),
    groups = area, stack = F, horizontal=F,xlab="Shell Length (mm)",ylab="Frequency (N)",
    scales=list(y=list(alternating=1,tck=-1,limits=c(0,400),
    at=c(0,50,100,150,200,250,300,350,400),
    labels=c("0","50","100","150","200","250","300","350","400"),relation="same")),
    par.settings = list( grid.pars = list(fontfamily = 'serif'),axis.line=list(col=0)),
    panel = function(...) {
           lims<-current.panel.limits()
             panel.barchart(...)
           panel.abline(v=as.factor(80),col="red",lty=2)
           panel.abline(v=as.factor(90),h=0,col="black")
           panel.abline(h=lims$ylim[1],v=lims$xlim[1])
           panel.text(25,200,"OC (N = 1,947)",col="black",cex=.8)
           panel.text(25,185,"ES (N = 2,623)",col="lightslategray",cex=.8)
           panel.text(25,170,"VB (N = 2,780)",col="light gray",cex=.8)
      })

当我在图表上运行代码时,一条垂直线,但第二行没有显示。无论我把什么值作为v,一行都不会改变位置。

R信息

R version 3.2.1 (2015-06-18)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252 
[2] LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets 
[7] methods   base     

other attached packages:
 [1] plyr_1.8.3          Hmisc_3.17-0        ggplot2_1.0.1      
 [4] Formula_1.2-1       survival_2.38-1     car_2.0-26         
 [7] MASS_7.3-40         xlsx_0.5.7          xlsxjars_0.6.1     
[10] rJava_0.9-7         latticeExtra_0.6-26 RColorBrewer_1.1-2 
[13] lattice_0.20-31 

任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

您将bin转换为代码开头的因子(尽管它会被强制转换为因子,即使您没有)也会创建一个隐式主刻度线坐标为1和2的分类轴作为每组酒吧的中心,而不是你期望的85和90。例如,请参阅更改代码时发生的情况,如下所示:

       panel.abline(v=1,col="red",lty=2)
       panel.abline(v=2,h=0,col="black")
       panel.abline(h=lims$ylim[1],v=lims$xlim[1])
       panel.text(1,200,"OC (N = 1,947)",col="black",cex=.8)
       panel.text(1.5,185,"ES (N = 2,623)",col="lightslategray",cex=.8)
       panel.text(2,170,"VB (N = 2,780)",col="light gray",cex=.8)
     })

答案 1 :(得分:1)

barchart(data$num~as.factor(data$bin), groups=data$area, 
panel=function(x,y,...){ 
       panel.barchart(x,y,...) 
       panel.abline(v=1,col.line="red",lty=3)
       panel.abline(v=2,col.line="blue",lty=2)})

以上应该这样做。

enter image description here