SecretIndividual
SecretIndividual

Reputation: 2519

Add legend to geom_line() plot

I would like to add a legend to the plot resulting from this code:

library(ggplot2)

v1 <- c(4.5, 4.5, 4.5, 5)
v2 <- c(3.5, 3, 3, 3.5)
v3 <- c(3, 4.5, 4, 3)
afname <- c(1, 2, 3, 4)

df <- data.frame(v1, v2, v3, afname)

df$afname <- as.factor(df$afname)

ggplot(df, aes(x = afname, group = 1)) +
  geom_line(aes(y = v1), size= 1, color = "blue") +
  geom_line(aes(y = v2), size= 1, color = "red") +
  geom_line(aes(y = v3), size= 1, color = "green") +
  ylim(2, 5) +
  ylab("vraag")

How would this be done?

Upvotes: 0

Views: 360

Answers (2)

KoenV
KoenV

Reputation: 4283

You could use the follow code, that first transforms your data in a tidy dataset: because this is what ggplot expects. For that reason, we use gather from tidyr

your data looked like this:

df
   v1  v2  v3 afname
1 4.5 3.5 3.0      1
2 4.5 3.0 4.5      2
3 4.5 3.0 4.0      3
4 5.0 3.5 3.0      4

after gathering it looks like the following:

df2
   afname Group vraag
1       1    v1   4.5
2       2    v1   4.5
3       3    v1   4.5
4       4    v1   5.0
5       1    v2   3.5
6       2    v2   3.0
7       3    v2   3.0
8       4    v2   3.5
9       1    v3   3.0
10      2    v3   4.5
11      3    v3   4.0
12      4    v3   3.0

So the following code produces the desired plot with the legend (generated by ggplot without you explicitly coding for it)

library(ggplot2)
library(tidyr)

df2 <- gather(df, Group, vraag, -afname)
ggplot(df2, aes(x = afname, y= vraag, col = Group, group = Group)) + 
  geom_line() +
  scale_y_continuous(limits = c(2,5))

This yields the following plot:

enter image description here

Upvotes: 1

Ian Campbell
Ian Campbell

Reputation: 24770

One approach is to pivot the data so you can use the mapping of ggplot:

library(ggplot2)
library(dplyr)
library(tidyr)
df %>%
  pivot_longer(-afname,names_to = "group") %>% 
ggplot(aes(x = as.numeric(afname), y = value, color = group)) +
  geom_line() +
  scale_color_discrete(labels = c("Label 1","Label 2", "Label 3")) + 
  ylim(2, 5) +
  ylab("vraag") + xlab("afname")

enter image description here

Upvotes: 1

Related Questions