O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

To add labels and legends, perform the following steps:

  1. Create the box plot:
> p <- ggplot(toothgrowth, aes(x=dose, y=len)) + geom_boxplot()
  1. Add the main title and labels to the x and y axes:
> p + ggtitle("Tooth growth Length vs Dose(mg/day) ") + xlab("Dose of Vitamin C(mg/day)") + ylab("Tooth Length")
  1. Add legends and a title to the plot:
> p_leg <- ggplot(toothgrowth, aes(x=dose, y=len, fill=as.factor(dose))) + geom_boxplot()> p_leg + labs(fill = "Dose (mg)")
  1. To move the legend from the default place:
> p_leg + labs(fill ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required