TomJohn
TomJohn

Reputation: 747

ggplot2 - Labels below line plot

Please consider following code:

library(ggplot2)

data<-mtcars
data$hp2<-mtcars$hp+50

data_long <- reshape2::melt(data[c('cyl', 'hp', 'hp2')], id.vars = 'cyl')
head(data_long)

ggplot(data_long, aes(x = cyl, y = value, colour = variable)) +
  stat_summary(fun.y = mean, geom = "line", show.legend = FALSE) + 
  stat_summary(fun.y = mean, geom = "text", show.legend = FALSE,  vjust=-0.7, aes( label=round(..y.., digits=0))) +
  scale_color_manual(values = c("red", "blue"))

is there a possibility to change behaviour of text labels for red curve? I.e. show them below the red line?

Upvotes: 1

Views: 65

Answers (1)

Humpelstielzchen
Humpelstielzchen

Reputation: 6441

You can assign a vector to vjust= for each value to assign its place.

ggplot(data_long, aes(x = cyl, y = value, colour = variable)) +
  stat_summary(fun.y = mean, geom = "line", show.legend = FALSE) + 
  stat_summary(fun.y = mean, geom = "text", show.legend = FALSE,  
               vjust= rep(c(1.4, -0.7), each = 3), aes( label=round(..y.., digits=0))) +
  scale_color_manual(values = c("red", "blue"))

enter image description here

Upvotes: 1

Related Questions