【问题标题】:Draw lines between two facets in ggplot2在ggplot2中的两个方面之间画线
【发布时间】:2014-08-26 23:50:11
【问题描述】:

如何在两个面之间画几条线?

我通过在顶部图表的最小值处绘制点来尝试此操作,但它们不在两个方面之间。见下图。

这是我目前的代码:

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

【问题讨论】:

  • 如何使用 grid.lines 包中的 grid
  • , panel.background = element_rect(colour="black") 添加到您的theme

标签: r plot ggplot2 visualization


【解决方案1】:

为了实现这一点,您必须将绘图内的边距设置为零。你可以通过expand=c(0,0) 做到这一点。我对您的代码所做的更改:

  • 当您使用scale_y_continuous 时,您可以在该部分内定义轴标签,不需要单独的ylab
  • geom_line 内将colour=I("black") 更改为colour="black"
  • 已将expand=c(0,0) 添加到scale_x_continuousscale_y_continuous

完整代码:

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"))

给出:


也可以使用geom_segment 添加行。通常,线条(线段)将出现在两个方面。如果您希望它们出现在两个方面之间,则必须在data 参数中进行限制:

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"))

给出:

【讨论】:

  • 我使用 geom_point 来绘制我想要的线条。这些行可以是不连续的。所以我的问题是如何在两个图的中间添加这些绿线。
  • @Enrique 查看我的更新答案,这是您要找的吗?
  • @Enrique 查看我更新的答案,我还添加了另一种绘制线条的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 2020-02-11
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多