Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 plot 3 factors with some x-axis jigging

Tags:

r

ggplot2

I want to make a points plot with ggplot2 geom_point where a continuous variable is stratified by different factors.

It is quite complicated, perhaps I am trying to show too much in one graph, but I have three different factors that influence things

I want to show it like this

p <- ggplot(mtcars[,c(1,2,10,11)], aes(factor(cyl), mpg))
p + geom_point(aes(colour = factor(gear), shape=factor(carb)))

enter image description here

However I want to split the factor(gear) out, i.e. for each of the three factor(cyl) value on the x axis, I want a small distance between the different factor(gear) colours on the x axis

i.e. within factor(cyl) == 4, factor(gear) == 3 is sort of on 3.9, factor(gear) == 4 is on 4 and factor(gear) == 5 is sort of on 4.1. This repeated for each factor(cyl) value.

Hope that makes sense

NB this is a toy example. I would be doing it using categorical, non-numeric values instead of factorised numbers; I realise having values on 3.9/4.1 is confusing.

like image 898
Jim Bo Avatar asked Jun 26 '12 10:06

Jim Bo


2 Answers

With facet_grid() and mtcars example:

library(ggplot2)
data(mtcars)

p <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_point(aes(colour=factor(carb)))
p + facet_grid(. ~ gear)

By number of gears

like image 55
John Avatar answered Sep 20 '22 12:09

John


subset is one way to do this. Subset the data by gears, then position the set of points for each subset in turn.

library(ggplot2)

p <- ggplot()
p + geom_point(data = subset(mtcars[,c(1,2,10,11)], gear == 3), aes(x = as.numeric(factor(cyl)) - 0.1, y = mpg, colour = factor(gear), shape=factor(carb))) +
    geom_point(data = subset(mtcars[,c(1,2,10,11)], gear == 4), aes(x = as.numeric(factor(cyl)), y = mpg, colour = factor(gear), shape=factor(carb))) +
    geom_point(data = subset(mtcars[,c(1,2,10,11)], gear == 5), aes(x = as.numeric(factor(cyl)) + .1, y = mpg, colour = factor(gear), shape=factor(carb))) +
   scale_x_continuous("Cylinders", breaks = c(1,2,3), labels = c(4,6,8), expand = c(.2,0))

enter image description here

like image 32
Sandy Muspratt Avatar answered Sep 18 '22 12:09

Sandy Muspratt