簡體   English   中英

ggplot2 2 行來自具有 3 個變量的數據

[英]ggplot2 2 lines from data with 3 variables

我的輸入數據如下所示:

            start_time              middle                 end RN
1: 2017-01-31 17:12:00 2017-01-31 17:40:00 2017-01-31 18:08:00  1
2: 2017-01-31 17:45:00 2017-01-31 19:03:00 2017-01-31 19:29:00  2
3: 2017-01-31 17:46:00 2017-01-31 17:48:00 2017-01-31 19:27:00  3
4: 2017-01-31 17:51:00 2017-01-31 18:40:00 2017-01-31 20:02:00  4
5: 2017-01-31 17:52:00 2017-01-31 19:52:00 2017-01-31 19:54:00  5
6: 2017-01-31 18:12:00 2017-01-31 18:46:00 2017-01-31 18:50:00  6

我想對此進行 ggplot,以便對於每個“RN”我想要一條從 start_time 到中間的線,以及從中間到結束的另一條線,這些線應該是不同的顏色。

在 x 軸上我想要時間,在 y 軸上我想要“RN”

我怎樣才能做到這一點?

編輯:這是我嘗試過的

melted <- melt(input_data, measure.vars = c("start_time", "middle", "end"))

ggplot(melted[variable != "end"], aes(value,RN)) + geom_line(size=1, colour="red")
  + geom_line(data = melted[variable != "start_time"], size=2)

我沒有反對,但老實說,我並不完全清楚你想繪制什么。 以下與您的“我想要 ggplot 這個一致,以便對於每個“RN”我想要一條從 start_time 到中間的線,以及從中間到結束的另一條線,這些線應該是不同的顏色。

# Your sample data
df <- read.table(text =
    "start_time              middle                 end RN
1 '2017-01-31 17:12:00' '2017-01-31 17:40:00' '2017-01-31 18:08:00'  1
2 '2017-01-31 17:45:00' '2017-01-31 19:03:00' '2017-01-31 19:29:00'  2
3 '2017-01-31 17:46:00' '2017-01-31 17:48:00' '2017-01-31 19:27:00'  3
4 '2017-01-31 17:51:00' '2017-01-31 18:40:00' '2017-01-31 20:02:00'  4
5 '2017-01-31 17:52:00' '2017-01-31 19:52:00' '2017-01-31 19:54:00'  5
6 '2017-01-31 18:12:00' '2017-01-31 18:46:00' '2017-01-31 18:50:00'  6", 
header = T, row.names = 1)


require(lubridate);
require(tidyverse);

df %>%
    mutate(
        start_time = ymd_hms(start_time),
        middle1 = ymd_hms(middle),
        middle2 = ymd_hms(middle),
        end = ymd_hms(end),
        RN = as.factor(RN)) %>%
    select(-middle) %>%
    gather(Date, Time, c(1:2, 4:5)) %>%
    mutate(Stage = ifelse(Date == "start_time" | Date == "middle1", "start-middle", "middle-end")) %>%
    ggplot(aes(x = Time, y = RN, col = Stage)) + geom_line()

在此處輸入圖片說明

暫無
暫無

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

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