2016-01-07 31 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