R 在ggplot2中的两个面之间绘制线
如何在两个面之间画几条线 我尝试在顶部图形的最小值处绘制点,但它们不在两个面之间。见下图 这是我目前的代码:R 在ggplot2中的两个面之间绘制线,r,plot,ggplot2,visualization,R,Plot,Ggplot2,Visualization,如何在两个面之间画几条线 我尝试在顶部图形的最小值处绘制点,但它们不在两个面之间。见下图 这是我目前的代码: 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)) po
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
t为了实现这一点,必须将绘图内的边距设置为零。您可以使用expand=c(0,0)
来实现这一点。我对您的代码所做的更改:
- 当您使用
scale\u y\u continuous
时,您可以在该零件内定义轴标签,而不需要单独的ylab
- 将
color=I(“黑色”)
更改为color=“黑色”
内部geom\u线
- 添加了
expand=c(0,0)
到scale\u x\u continuous
和scale\u y\u 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_段
添加行。通常,直线(段)将出现在两个面中。如果希望它们出现在两个面之间,则必须在数据中限制该参数:
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"))
其中:
如何使用grid.lines
从packagegrid
添加,panel.background=element\u rect(color=“black”)
到您的主题中
我使用geom\u点绘制了我想要的线条。这些行可以是非连续的。所以我的问题是如何在两个图的中间添加这些绿色线条。“恩里克,看我的更新答案,这就是你要找的吗?”恩里克看到我的更新答案,我还添加了另一种绘制线条的方法。