如何在双Y轴图中对齐条形图和线形图

时间:2018-09-11 18:45:52

标签: r bar-chart linechart

我正在尝试创建一个具有两个Y轴的图。我修改了HEREBen Bolker给出的一个很好的答案,并且效果很好。 enter image description here 现在,我想用barplot替换一个折线图,但是由于某种原因,我的barplot和折线图无法很好地对齐。 enter image description here

我的代码如下

## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(500,1000,2000,3000,4000,5000,6000)
se1 <- c(0.01,0.02,0.03,0.04,0.05,0.06,0.07)
se2 <- c(50,100,200,300,400,500,300)
## Plot first set of data and draw its axis
barCenters <- barplot(height = cell.density, 
                      beside = TRUE, 
                      las = 1,
                      ylim = c(0, 7000),
                      axes=FALSE,
                      type="b"
)
## a little farther out (line=4) to make room for labels
mtext("Relative expression",side=4,col="black",line=4, las=0) 
axis(4, ylim=c(0,7000), col="black",col.axis="black",las=1)
segments(barCenters, cell.density  - se2 * 2, barCenters,
         cell.density + se2 * 2, lwd = 1.5)
arrows(barCenters, cell.density - se2 * 2, barCenters,
       cell.density + se2 * 2, lwd = 1.5, angle = 90,
       code = 3, length = 0.05)
## Allow a second plot on the same graph
par(new=TRUE)
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="", 
     type="b",col="black", main="Test data")
arrows(time, betagal.abs, time, betagal.abs  + se1, length= 0.05,angle=90)
arrows(time, betagal.abs, time, betagal.abs  - se1, length= 0.05,angle=90)
axis(2, ylim=c(0,1),col="black",las=1)  ## las=1 makes horizontal labels
mtext("Relative activity",side=2,line=2.5)
box()

## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)  

## Add Legend
legend("topleft",legend=c("Relative activity","Relative expression"),
       text.col=c("black","black"),pch=c(16,15),col=c("black","black"))

任何建议都会有所帮助。谢谢

0 个答案:

没有答案