创建和组合两个图 - xy线图和R中的条形图

时间:2012-02-18 10:44:14

标签: r graph ggplot2 line-plot

我打算从以下两个数据集创建图表:

第一个数据(将开发底部)

position <- c(10, 26, 31, 50, 73, 92, 120, 124)  # need scale 
    minimum 0 to maximum 130
label <- c("A", "B", "C", "D", "E", "F", "G", "H")
mydf <- data.frame (position, label)

第二个数据(将显示叠加的线图)

pos <- 1:130
value <- seq (0, 1.29, 0.01) 
mydf2 <- data.frame (pos, value) 

图表希望开发(类似或更高质量):

enter image description here

我的试用

以下是我试过的,完全划伤!

yvar <- rep(1, length(position))

require (ggplot2)


bar <- data.frame(y = c(1, 1), x = c(0, 130))
ggplot() +
  geom_line(aes(x, factor(y), group = factor(y)),
            bar, size = 2, colour = "skyblue") +
  geom_rect(aes(y = yvar,
                 xmin = position - 0.1,
                 xmax = position + 0.1,
                 ymin = 1 - yvar /2,
                 ymax = 1 + yvar /2))

1 个答案:

答案 0 :(得分:3)

这是一个基础图形的解决方案。

# Split the plot area in two
layout(matrix(c(1,1,2),nc=1))
# First plot
plot( pos, value, type="l", las=1 )
# Reduce the margins for the second plot
m <- par()$mar
m[1] <- m[3] <- 0
par(mar=m)
# Set the limits of the second plot
plot( pos, pos-pos, type="n", axes=FALSE, xlab="", ylab="" )
# Add the rectangle, the segments and the text.
polygon( 
  c(0,max(mydf2$pos),max(mydf2$pos),0), 
  .2*c(-1,-1,1,1),
  col=rgb(.1,.5,.3)
)
segments( mydf$position, -.5, mydf$position, .5 )
text(mydf$position, -.7, mydf$label)
text(mydf$position,  .7, mydf$position)

enter image description here