Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you plot a box plot and specific points on the same plot?

Tags:

r

ggplot2

boxplot

We can draw box plot as below:

qplot(factor(cyl), mpg, data = mtcars, geom = "boxplot")

and point as:

qplot(factor(cyl), mpg, data = mtcars, geom = "point") 

How would you combine both - but just to show a few specific points(say when wt is less than 2) on top of the box?

like image 273
Neerav Avatar asked Feb 13 '12 04:02

Neerav


1 Answers

If you are trying to plot two geoms with two different datasets (boxplot for mtcars, points for a data.frame of literal values), this is a way to do it that makes your intent clear. This works with the current (Sep 2016) version of ggplot (ggplot2_2.1.0)

library(ggplot2)
ggplot() +
  # box plot of mtcars (mpg vs cyl)
  geom_boxplot(data = mtcars, 
               aes(x = factor(cyl), y= mpg)) +
  # points of data.frame literal
  geom_point(data = data.frame(x = factor(c(4,6,8)), y = c(15,20,25)),
             aes(x=x, y=y),
             color = 'red')

I threw in a color = 'red' for the set of points, so it's easy to distinguish them from the points generated as part of geom_boxplot

enter image description here

like image 191
arvi1000 Avatar answered Oct 07 '22 21:10

arvi1000