4

I have the following data frame summary created with dplyr

structure(list(maxrep = c(7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L, 11L, 
11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L, 17L, 17L, 
18L, 18L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 23L, 23L, 24L, 
24L, 26L, 26L), div = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("Premier Division", 
"Second Division"), class = "factor"), freq = c(1L, 10L, 4L, 
39L, 26L, 89L, 73L, 146L, 107L, 162L, 117L, 133L, 121L, 125L, 
116L, 91L, 110L, 65L, 95L, 43L, 75L, 38L, 43L, 24L, 38L, 16L, 
36L, 5L, 15L, 2L, 9L, 7L, 9L, 1L, 3L, 3L, 2L, 1L)), .Names = c("maxrep", 
"div", "freq"), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -38L))

My intention is to use ggplot2 to plot line graphs of 2 lines with different colour with text labels for each value.

What I did was

ggplot(df, aes(x=maxrep, y=freq, colour=div)) +
geom_line() +
geom_text(aes(label=freq), vjust=-.5)

The result was

enter image description here

Now my question: All the labels in the chart are above the points in respective lines. I want to have the labels for the different colours to be in different relative position, e.g. labels for cyan above the line, and labels for red below the line (i.e. variable vjust). Is there a way to do that?

Also, is there a way to get read of the letter a in the colour legend on the right?

Ricky
  • 4,616
  • 6
  • 42
  • 72

2 Answers2

5

What about plotting the lines separately wich differing vjust values? You can get rid of a in the legend setting show_guide = FALSE.

ggplot(df, aes(x=maxrep, y=freq, colour=div, label = freq)) +
    geom_line() +
    geom_text(data = df[df$div == "Second Division",], vjust=2, show_guide = FALSE) + geom_text(data = df[df$div == "Premier Division",], vjust=-2, show_guide = FALSE)

Which returns:

enter image description here

DatamineR
  • 10,428
  • 3
  • 25
  • 45
4

Create a new variable in the data.frame holding the vjust adjustment parameter:

df$pos <- c(2, -2)[(df$div == "Premier Division")+1] 

And you could call vjust inside aes with the new pos vector:

ggplot(df, aes(x=maxrep, y=freq, colour=div)) +
    geom_line() +
    geom_text(aes(label=freq, vjust=pos))

pic

talat
  • 68,970
  • 21
  • 126
  • 157
  • Thanks, this is great, I managed to adopt it for even more conditions. I actually tried this before I asked the question, but I didn't realise the `vjust` portion needs to be inside the `aes`. – Ricky Feb 02 '15 at 05:17