如何在两个面之间绘制多条线?
我尝试通过在顶部图表的最小值处绘制点来实现此目的,但它们不在两个方面之间。见下图。
这是我到目前为止的代码:
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_continuous
和scale_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"))
给出:
<小时/>添加线条也可以使用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"))
给出:
关于r - 在ggplot2中绘制两个面之间的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594628/