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

时间:2017-07-17 09:55:33

标签: r line bar-chart

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

这是一个可重复的例子:

dlib

使用此代码,图表的方式如下: enter image description here

1 个答案:

答案 0 :(得分: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