首页 文章

在条形图前面添加时间序列线

提问于
浏览
0

我想在条形图上添加一行 . 但是,当我使用下面的代码时,生成的行不适合绘图 - 它太短,即使该行的数据系列与barplot数据系列具有相同的长度 .

这是一个可重复的例子:

pos <- c(4,5,5,6,4,6,4,5.5,6,8,7)
neg <- c(-8,-7,-7,-7,-6,-7,-5,-6,-6.5,-9,-7)
net <- pos+neg

plot.par <- par(mfrow=c(1,1))
par(mar=c(4,4.5,2,1))
plot(pos, type="n", main="", cex.main=1.1, xlab="", 
     ylab="", cex.lab=1.3, yaxt= "n", xaxt="n", ylim=c(-10, 10))
abline(h=c(-10,-8,-6,-4,-2,0,2,4,6,8,10),col = grey(0.6), lty=3)
abline(v=c(1,4,7), 
       col = grey(0.6), lty=3)
par(new=T)
barplot(pos, main="", cex.main=1.1, xlab="", col="darkolivegreen", border="darkolivegreen",
        ylab="", cex.lab=1.1, yaxt= "n", xaxt="n", ylim=c(-10, 10))
par(new=T)
barplot(neg, main="", cex.main=1.1, xlab="", col="darkgoldenrod3",border="darkgoldenrod3",
        ylab="", cex.lab=1.1, yaxt= "n", xaxt="n", ylim=c(-10, 10))
par(new=T)
lines(net, col="firebrick4", lwd = 4)

使用此代码,该图看起来如下:
enter image description here

1 回答

  • 0

    你可以试试:

    # creating the barplots 
    h <- barplot(pos, ylim=c(-10,10), col="darkolivegreen", border="darkolivegreen", yaxt="n")
    barplot(neg, add=T, col="darkgoldenrod3",border="darkgoldenrod3",yaxt="n")
    
    # adding the horizontal ablines
    abline(h=c(-10,-8,-6,-4,-2,0,2,4,6,8,10),col = grey(0.6), lty=3)
    abline(v=h[c(1,4,7)], col = grey(0.6), lty=3)
    
    # plot the barplots again to overplot the ablines
    barplot(pos, ylim=c(-10,10), col="darkolivegreen", border="darkolivegreen",add=T)
    barplot(neg, add=T, col="darkgoldenrod3",border="darkgoldenrod3", yaxt="n")
    
    # add the line using x values stored in h...the true positions of the middle of each bar
    lines(x=h,y=net, col="firebrick4", lwd = 4)
    
    # the box around the plot
    box()
    

    enter image description here

    作为替代方案,您也可以使用ggplot2 . 使用 dplyrtidyr 完成数据准备 . 所有包都包含在超级包中 tidyverse

    library(tidyverse)
    d <- cbind.data.frame(id=seq_along(pos), pos, neg)
    d %>% mutate(net=pos+neg) %>% 
      gather(key, value, -id, -net) %>% 
      ggplot(aes(x=id, y=value, fill=key)) +
      geom_bar(stat="identity") +
      geom_line(aes(x=id, y=net), size=3) +
      theme_bw() +
      scale_x_continuous(breaks = c(1,4,7))+
      theme(axis.title.x=element_blank(),
            axis.text.x=element_blank(),
            axis.ticks.x=element_blank(),
            panel.grid.minor.x=element_blank())+
      ylim(-10,10)
    

    enter image description here

相关问题