Friday, May 11, 2012

Porting cdplot to ggplot2

Last week I published a post on plotting tables in ggplot2. So the next natural step is to port cdplot to allow simple visualization of categorical variables against a numerical predictor.
First part of the story covers binary variables. In this case the solution does not require using cdplot as one can use gam smoother. Here is the code that uses Participation data set from Ecdat package to visualize relationship between age and lfp:

library(ggplot2)
library(Ecdat)
library(mgcv)
data(Participation)
cdens <- with(Participation,
  cdplot(lfp~age, plot = FALSE, ylevels = 2:1))
ggplot() + geom_smooth(data = Participation,
  aes(x = age, y = as.integer(lfp) - 1),
  method="gam", formula=y~s(x), family="binomial",
  lwd=2, colour="black") +
  stat_function(fun=cdens[[1]], lwd = 1, colour = "red") +
  theme_bw() + xlab("age") + ylab("Pr(lfp = 1)")

On the plot below the black line is plotted using gam and the red one is derived from cdplot:


For categorical variables having more than two levels the situation is a bit more complex because it is not so easy to use gam-based solution. But using cdplot works in this case also. Here is the code using  iris data as an example:

library(ggplot2)
cdens <- cdplot(iris$Sepal.Length, iris$Species, plot = F)
x <- seq(min(iris$Sepal.Length), max(iris$Sepal.Length),
  length.out = 100)
y <- c(cdens[[1]](x), cdens[[2]](x), rep(1, length(x)))
type <- ordered(rep(levels(iris$Species), each = length(x)),
  levels=rev(levels(iris$Species)))
x <- rep(x, 3)
qplot(x, y, geom="area", fill = type, position="identity",
  xlab="Sepal.Length", ylab="Species") + theme_bw()

and the plot it generates looks as follows:


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.