Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable label position in ggplot line chart

Tags:

r

ggplot2

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?

like image 432
Ricky Avatar asked Jan 08 '23 23:01

Ricky


1 Answers

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

like image 119
DatamineR Avatar answered Jan 11 '23 19:01

DatamineR