Draw lines between two facets in ggplot2

拥有回忆 提交于 2019-12-23 19:43:42

问题


How can I draw several lines between two facets?

I attempted this by plotting points at the min value of the top graph but they are not between the two facets. See picture below.

This is my code so far:

t <- seq(1:1000)
y1 <- rexp(1000)
y2 <- cumsum(y1)
z <- rep(NA, length(t))
z[100:200] <- 1

df <- data.frame(t=t, values=c(y2,y1), type=rep(c("Bytes","Changes"), each=1000))
points <- data.frame(x=c(10:200,300:350), y=min(y2), type=rep("Bytes",242))
vline.data <- data.frame(type = c("Bytes","Bytes","Changes","Changes"), vl=c(1,5,20,5))

g <- ggplot(data=df, aes(x=t, y=values)) +
  geom_line(colour=I("black")) +
  facet_grid(type ~ ., scales="free") +
  scale_y_continuous(trans="log10") +
  ylab("Log values") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1), panel.margin = unit(0, "lines"))+
  geom_point(data=points, aes(x = x, y = y), colour="green")

g

回答1:


In order to achieve that, you have to set the margins inside the plot to zero. You can do that with expand=c(0,0). The changes I made to your code:

  • When you use scale_y_continuous, you can define the axis label inside that part and you don't need a seperarate ylab.
  • Changed colour=I("black") to colour="black" inside geom_line.
  • Added expand=c(0,0) to scale_x_continuous and scale_y_continuous.

The complete code:

ggplot(data=df, aes(x=t, y=values)) +
  geom_line(colour="black") +
  geom_point(data=points, aes(x = x, y = y), colour="green") +
  facet_grid(type ~ ., scales="free") +
  scale_x_continuous("t", expand=c(0,0)) +
  scale_y_continuous("Log values", trans="log10", expand=c(0,0)) +
  theme(axis.text.x=element_text(angle=90, vjust=0.5), panel.margin=unit(0, "lines"))

which gives:


Adding lines can also be done with geom_segment. Normally the lines (segments) will appear in both facets. If you want them to appear between the two facets, you will have to restrict that in data parameter:

ggplot(data=df, aes(x=t, y=values)) +
  geom_line(colour="black") +
  geom_segment(data=df[df$type=="Bytes",], aes(x=10, y=0, xend=200, yend=0), colour="green", size=2) +
  geom_segment(data=df[df$type=="Bytes",], aes(x=300, y=0, xend=350, yend=0), colour="green", size=1) +
  facet_grid(type ~ ., scales="free") +
  scale_x_continuous("t", expand=c(0,0)) +
  scale_y_continuous("Log values", trans="log10", expand=c(0,0)) +
  theme(axis.text.x=element_text(angle=90, vjust=0.5), panel.margin=unit(0, "lines"))

which gives:



来源:https://stackoverflow.com/questions/24594628/draw-lines-between-two-facets-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!