Porting cdplot to ggplot2

May 11, 2012

(This article was first published on R snippets, and kindly contributed to R-bloggers)

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:

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:
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)),
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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Dommino data lab

Quantide: statistical consulting and training




CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

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)