简体   繁体   English

在ggplot上绘制与折线图相交的垂直/水平线

[英]Plotting vertical/horizontal lines that intersect line graph on ggplot

The following code produces the following plot:以下代码生成以下图:

time_step <- c(1:5, 1:5)

perceived_signal_slow <- c(1:5, cumsum(1:5))

signal_name <- c("perceived","perceived","perceived","perceived","perceived","accumulated","accumulated","accumulated","accumulated","accumulated")

df <- cbind(perceived_signal_slow, signal_name, time_step)

df <- as.data.frame(df)

df$time_step <- as.numeric(as.character(df$time_step))
df$perceived_signal_slow <- as.numeric(as.character(df$perceived_signal_slow))

ggplot(df, aes(x = time_step, y = signal, colour = signal_name)) +
  geom_line() +
  geom_vline(xintercept = 4, colour = "black", size = 1, alpha = .4) +
  geom_hline(yintercept = 10, colour = "black", size = 1, alpha = .4) +
  geom_hline(yintercept = 4, colour = "black", size = 1, alpha = .4)

阴谋 However I want to limit the vertical and horizontal lines so that they don't travel any further once they hit the accumulated and perceived lines of my graph.但是,我想限制垂直线和水平线,这样它们一旦碰到我的图形的累积线和感知线就不会进一步移动。 Does anybody know how I could alter my code to do this?有谁知道我如何改变我的代码来做到这一点?

Thanks in advance for the help!在此先感谢您的帮助!

We could use geom_segment :我们可以使用geom_segment

time_step <- c(1:5, 1:5)

perceived_signal_slow <- c(1:5, cumsum(1:5))

signal_name <- c("perceived","perceived","perceived","perceived","perceived","accumulated","accumulated","accumulated","accumulated","accumulated")

df <- cbind(perceived_signal_slow, signal_name, time_step)

df <- as.data.frame(df)

df$time_step <- as.numeric(as.character(df$time_step))
df$signal <- as.numeric(as.character(df$perceived_signal_slow))

library(ggplot2)
ggplot(df, aes(x = time_step, y = signal, colour = signal_name)) +
  geom_line() +
  geom_segment(x = 4, xend=4, y = -Inf, yend=10, colour = "black", size = 0.2) +
  geom_segment(x= -Inf, xend=4, y = 10, yend = 10, colour = "black", size = 0.2) +
  geom_segment(x= -Inf, xend=4, y = 4, yend = 4, colour = "black", size = 0.2)

This produces:这产生:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM