Porting cdplot to ggplot2

[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:


To leave a comment for the author, please follow the link and comment on their blog: R snippets.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)