creating and combining two plots - xy line plot with bar chain plot in R
Question
The following two data sets I intend create graph from:
first data (will develop bottom portion)
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)
second data (will develop line plot over layed)
pos <- 1:130
value <- seq (0, 1.29, 0.01)
mydf2 <- data.frame (pos, value)
The graph want to develop (similar or higher quality):
My trial
The following is what I tried, complete scratch !
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))
Solution
Here is a solution with base graphics.
# 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow