TomJohn
TomJohn

Reputation: 747

ggplot2 - How to add additional text labels

I am having some trouble with ggplot and stat_summary.

Please consider following data:

head(mtcars)
data<-mtcars
data$hp2<-mtcars$hp+50

Please consider following code:

ggplot(mtcars, aes(x = cyl, y = hp)) +
stat_summary(aes(y = hp, group = 1), fun.y=mean, colour="red", geom="line",group=1) + 
stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, vjust=-0.7, aes( label=round(..y.., digits=0)))

The code will produce line plot with means of hp and text labels for means ans well. If we would like to add another line/curve we simply have to add:

ggplot(mtcars, aes(x = cyl, y = hp)) +
stat_summary(aes(y = hp, group = 1), fun.y=mean, colour="red", geom="line",group=1) + 
stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,  vjust=-0.7, aes( label=round(..y.., digits=0)))+
stat_summary(aes(y = hp2), fun.y=mean, colour="blue", geom="line",group=1) 

Now comes the tricky part:

How to use stat_summary with geom="text" but for the hp2 i.e. how to technically force stat_summary to calculate means on hp2 and print the text labels? It seems that I can only use it for the "main" y.

Upvotes: 0

Views: 455

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

This type of problem, that asks for graphs of related vector columns, is almost always a wide-to-long data format reshaping problem.

library(ggplot2)

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"))

enter image description here

Upvotes: 2

Related Questions