0

I have a graph that I'm trying to add a legend to but I can't find any answers. Here's what the graph looks like

enter image description here

I made a dataframe containing my x-axis as a colum and several othe columns containing y values that I graphed against x (fixed) in order to get these curves. I want a legend to appear on the side saying column 1, ...column 11 and corresponding to the color of the graph How do I do this? I feel like I'm missing something obvious

Here's what my code looks like:(sorry for the pic. I keep getting errors that my code is not formatted correctly even though I'm using the code button)

enter image description here

interval is just 2:100 and aaaa etc... is a vector the same length as interval.

Jama
  • 113
  • 5
  • 2
    Maybe modify the data into 'long' format? look at `tidyr::pivot_longer(y, ...)` It would help if the question included a reproducible dataset as well as code. – Peter Oct 26 '22 at 07:03

1 Answers1

0

As Peter says, you will need to convert your data into "long" format. Here is an example using reshape2::melt:

library(reshape2)
library(ggplot2)

n <- 20
df <- data.frame(x = seq(n))

tmp <- as.data.frame(do.call("cbind", lapply(seq(5), FUN = function(x){rnorm(n)})))
names(tmp) <- paste0("aaaa", letters[1:5])
df <- cbind(df, tmp)
head(df)

df2 <- melt(df, id.vars = "x")
head(df2)

ggplot(data = df2) + aes(x = x, y = value, color = variable) +
  geom_point() +
  geom_line()

enter image description here

Marc in the box
  • 11,769
  • 4
  • 47
  • 97
  • Thanks for the response. Could explain what tmp as you have defined it is doing.How about melt? – Jama Oct 30 '22 at 06:09