2016-01-07 84 views
1

我想知道是否有另一種方法來獲得相同的圖形或可以編輯圖例,而無需更改所有字符串與「第一」,「第二」,「圖例」有一個新的傳說。繪製許多不同長度的線

「First」和「Second」的數據具有不同的長度。

的代碼是:預先

First <- c(71.54,76.48,77.58,63.80,66.16,73.22,70.71,72.94,73.22,69.37,70.49,72.25,70.94,71.54,71.01,68.36,70.46,69.22,75.98,73.66,72.90,75.74,73.55,79.48,76.37,64.62,65.86,70.08,73.40,79.72,57.43) 

Second <- c(80.61,79.03,80.35,77.52,79.16,80.80,80.49,82.00,83.16,84.15,80.16,84.30,84.01,80.81,81.69,82.79,81.41,80.45,79.85,79.81,84.70,85.22,80.51,82.39,83.43,82.39,81.91,81.89,82.00,82.14,83.30,74.11) 

a2 <- data.frame(Seq=seq(0, (length(First) - 1) * 3, by = 3), All=First) 
a4 <- data.frame(Seq=seq(0, (length(Second) - 1) * 3, by = 3), All=Second) 

sg <- rbind(a2,a4) 
sg$Legend <- c(rep("First", nrow(a2)), rep("Second", nrow(a4))) 
ggplot(data=sg, aes(x=Seq, y=All, col=Legend)) + geom_line() 

And the plot is here:

感謝。

+1

你的意思是使用'long'格式data.frame?是的,這是做到這一點的方法。 –

+0

但還有另一種方法可以做到嗎?以及如何更新圖例而不需要超過1次更改「第一個」字符串? –

+0

您可以使用['dplyr :: bind_rows'](http://finzi.psych.upenn.edu/library/dplyr/html/bind.html)和'.id'變量來縮短它,如果這就是你所追求的。 – Axeman

回答

2

一般來說,你現在正在做的是好的。以長格式獲取數據並將變量映射爲顏色。在這裏看到三個替代方案來獲得(大約)相同的情節。

library(ggplot2) 

First <- c(71.54,76.48,77.58,63.80,66.16,73.22,70.71,72.94,73.22,69.37,70.49,72.25,70.94,71.54,71.01,68.36,70.46,69.22,75.98,73.66,72.90,75.74,73.55,79.48,76.37,64.62,65.86,70.08,73.40,79.72,57.43) 
Second <- c(80.61,79.03,80.35,77.52,79.16,80.80,80.49,82.00,83.16,84.15,80.16,84.30,84.01,80.81,81.69,82.79,81.41,80.45,79.85,79.81,84.70,85.22,80.51,82.39,83.43,82.39,81.91,81.89,82.00,82.14,83.30,74.11) 

方法1:bind_rows

dat1a <- data.frame(Seq=seq(0, (length(First) - 1) * 3, by = 3), 
        All=First) 
dat1b <- data.frame(Seq=seq(0, (length(Second) - 1) * 3, by = 3), 
        All=Second) 
dat1 <- dplyr::bind_rows(dat1a, dat1b, .id = 'Legend') 

ggplot(data=dat1, aes(x=Seq, y=All, col=Legend)) + geom_line() 

enter image description here

方法2:聚集

dat2 <- data.frame(Seq=seq(0, (max(length(First), length(Second)) - 1) * 3, by = 3), 
        First = c(First, NA), 
        Second = Second) 
dat2 <- tidyr::gather(dat2, 'Legend', 'All', -Seq) 

ggplot(data=dat2, aes(x=Seq, y=All, col=Legend)) + geom_line() 

enter image description here

方法3:單獨geoms

ggplot(mapping = aes(x=Seq, y=All)) + 
    geom_line(data = dat1a, aes(col = 'First')) + 
    geom_line(data = dat1b, aes(col = 'Second')) 

enter image description here