rggplot2direct-labels

How to use direct.label() with simple (two variables) ggplot2 chart


Here is a simple ggplot chart for two variables:

library("ggplot2")
library("directlabels")
library("tibble")

df <- tibble(
  number = 1:10,
  var1 = runif(10)*10,
  var2 = runif(10)*10
)

ggplot(df, aes(number))+
  geom_line(aes(y=var1), color='red')+
  geom_line(aes(y=var2), color='blue')

Is it possible to label the last value of var1 and var2 using the expression like that:

direct.label(df, 'last.points')

In my case I get an error:

Error in UseMethod("direct.label") : 
  no applicable method for 'direct.label' applied to an object of 
class

Solution

  • Maria, you initially need to structure your data frame by "stacking data". I like to use the melt function of the reshape2 package. This will allow you to use only one geom_line.

    Later you need to generate an object from ggplot2. And this object you must apply the directlabels package.

    library(ggplot2)
    library(directlabels)
    library(tibble)
    library(dplyr)
    library(reshape2)
    set.seed(1)
    df <- tibble::tibble(number = 1:10,
                         var1 = runif(10)*10,
                         var2 = runif(10)*10)
    
    df <- df %>% 
      reshape2::melt(id.vars = "number")
    p <- ggplot2::ggplot(df) +
      geom_line(aes(x = number, y = value, col = variable), show.legend = F) +
      scale_color_manual(values = c("red", "blue"))
    p
    

    enter image description here

    directlabels::direct.label(p, 'last.points') 
    

    enter image description here