0

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
MariaMaria1
  • 25
  • 1
  • 6

1 Answers1

0

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

bbiasi
  • 1,549
  • 2
  • 15
  • 31
  • Note that `reshape2` is retired and it is recommended to use `tidyr` instead. i.e. use `df <- df %>% tidyr::gather(variable, value, 2:3)` instead of `reshape2::melt`. (See https://cran.r-project.org/web/packages/reshape2/README.html) – Sarah May 02 '19 at 03:47