绘制许多不同长度的线

时间:2016-01-07 07:40:42

标签: r ggplot2

我想知道是否有其他方法可以获得相同的图形或者可以编辑图例而无需使用" First"," Second",&#34更改所有字符串;图例"有一个新的传奇。

" First"的数据和"第二"有不同的长度。

代码是:

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 个答案:

答案 0 :(得分: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

相关问题