簡體   English   中英

在ggplot上繪制與折線圖相交的垂直/水平線

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

以下代碼生成以下圖:

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)

陰謀 但是,我想限制垂直線和水平線,這樣它們一旦碰到我的圖形的累積線和感知線就不會進一步移動。 有誰知道我如何改變我的代碼來做到這一點?

在此先感謝您的幫助!

我們可以使用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)

這產生:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM