[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.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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)< o:p>
library(Ecdat)< o:p>
library(mgcv)< o:p>
data(Participation)< o:p>
cdens <- with(Participation,< o:p>
cdplot(lfp~age, plot = FALSE, ylevels = 2:1))< o:p>
ggplot() + geom_smooth(data = Participation,< o:p>
aes(x = age, y = as.integer(lfp) – 1),< o:p>
method=“gam”, formula=y~s(x), family=“binomial”,< o:p>
lwd=2, colour=“black”) +< o:p>
stat_function(fun=cdens[[1]], lwd = 1, colour = “red”) +< o:p>
theme_bw() + xlab(“age”) + ylab(“Pr(lfp = 1)”)< o:p>
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)< o:p>
cdens <- cdplot(iris$Sepal.Length, iris$Species, plot = F)< o:p>
x <- seq(min(iris$Sepal.Length), max(iris$Sepal.Length),< o:p>
length.out = 100)< o:p>
y <- c(cdens[[1]](x), cdens[[2]](x), rep(1, length(x)))< o:p>
type <- ordered(rep(levels(iris$Species), each = length(x)),< o:p>
levels=rev(levels(iris$Species)))< o:p>
x <- rep(x, 3)< o:p>
qplot(x, y, geom=“area”, fill = type, position=“identity”,< o:p>
xlab=“Sepal.Length”, ylab=“Species”) + theme_bw()< o:p>
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.