Christian Silva
Christian Silva

Reputation: 91

Plotting many lines of different lengths

I want to know if there is another way to get the same graphic or can edit the legend without need to change all string with "First", "Second", "Legend" to have a new legend.

Data for "First" and "Second" have different lengths.

The code is:

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:

Thanks in advance.

Upvotes: 1

Views: 1450

Answers (1)

Axeman
Axeman

Reputation: 35402

In general, what you are doing now is good. Get the data in long format and map a variable to color. See here for three alternatives to get (approximately) the same plot.

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)

Method 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

Method 2: gather

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

Method 3: separate 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

Upvotes: 3

Related Questions