Adding Multiple Lines on Same plot

Hi, I am trying to add multiple sets of data onto the same plot. My data sets on the X range from 0 to 1, but the Y varies. The issue I'm running into is that each set of data are not the same length. I would like to have each set of data to have its own color as well.

Any help would be extremely appreciated.

Welcome to the community!

This is indeed possible, and here's a small example.


set.seed(seed = 49728)

data_1 <- data.frame(u = seq(from = 0,
                             to = 1,
                             length.out = 4),
                     v = runif(n = 4))

data_2 <- data.frame(u = seq(from = 0,
                             to = 1,
                             length.out = 16),
                     v = rexp(n = 16))

data_3 <- data.frame(u = seq(from = 0,
                             to = 1,
                             length.out = 64),
                     v = rnorm(n = 64))

ggplot(mapping = aes(x = u,
                     y = v)) +
  geom_line(data = data_1,
            colour = "red",
            linetype = "solid") +
  geom_line(data = data_2,
            colour = "blue",
            linetype = "dotted") +
  geom_line(data = data_3,
            colour = "green",
            linetype = "dashed")

Created on 2020-01-17 by the reprex package (v0.3.0)

For your future questions, please provide a reproducible example.

1 Like

You can stack your data sets into a single "long" data frame, which will then require only one call to geom_line() and automate the creation of a legend marking the data source for each line. I've also added code to manually set the colors and line types in case you want to change them from the default values. The code below uses @Yarnabrina's sample data.


# Stack the three data frames into a single "long" data frame 
#  and pipe it into ggplot
map_df(paste0("data_", 1:3) %>% set_names(), get, .id="source") %>% 
  ggplot(aes(u, v, colour=source, linetype=source)) +
    geom_line() +
    scale_colour_manual(values=c("red","blue","green")) +



This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.