r - 在ggplot2中绘制两个面之间的线

标签 r plot ggplot2 visualization

如何在两个面之间绘制多条线?

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

enter image description here

这是我到目前为止的代码:

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

最佳答案

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

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

完整代码:

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

给出: enter image description here

<小时/>

添加线条也可以使用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"))

给出: enter image description here

关于r - 在ggplot2中绘制两个面之间的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594628/

相关文章:

python - 使用 ggplot 更改 x 轴刻度标签

html - 包括带有 knitr 的交互式 3D 人偶

r - Quantmod Heikin-Ashi 绘图不可用

r 错误 dim(X) 必须具有正长度?

r - 在 R 中使用 XGBoost 预测类变量

python - "%"登录 matplotlib Python

Python Matplotlib : plotting feet and inches

python - 刷新剧情 Chaco

r - 在一个图中对齐两个图例

r - 自动调整使用 ggplot2 绘制的图例的大小,使整个图例位于图层的边界内