Duke
Duke

Reputation: 55

How to add legend on a line plot?

I have a data like this

    year    catch   group
    2011    22       1
    2012    45       1
    2013    34       1
    2011    11       2
    2012    22       2
    2013    32       2

I would like to have the number of the group (1 and 2) to appear above the line in the plot. Any suggestion?

My real data has 8 groups in total with 8 lines which makes it hard to see because the lines cross one another and the colors of the legend are similar.

I tried this:

library(ggplot2)
ggplot(aes(x=as.factor(year), y=catch, group=as.factor(group), 
           col=as.factor(group)), data=df) +
  geom_line() +
  geom_point() +
  xlab("year") + 
  labs(color="group")

Upvotes: 0

Views: 32

Answers (1)

MrGumble
MrGumble

Reputation: 5776

Firstly, distinguishing 8 different colours is very difficult. That's why your 8 groups seem to have similar colors.

What you want in this case is not a legend (which usually is an off-chart summary), but rather "annotation". You can directly add the groups with

ggplot(...) +
geom_text(aes(x=as.factor(year), y=catch, label=group)) +
...

and then try to tweak the position of the text with nudge_x and nudge_y. But if you wanted only 1 label per group, you would have to prepare a data frame with it:

labels <- df %>% group_by(group) %>% top_n(1, -year)
ggplot(...) +
geom_text(data=labels, aes(x=as.factor(year), y=catch, label=group)) +
...

Upvotes: 1

Related Questions