[R] Conditional density plot in lattice

Deepayan Sarkar deepayan.sarkar at gmail.com
Thu Jan 21 19:30:32 CET 2010


On Thu, Jan 21, 2010 at 9:05 AM, Dieter Menne
<dieter.menne at menne-biomed.de> wrote:
> Dear group,
>
> I want to create a plot similar to cdplot or cd_plot I vcd :
>
> http://addictedtor.free.fr/graphiques/graphcode.php?graph=120
>
> with lattice and support for multiple panels. Densities should not be
> computed, these are stored in a data frame as in the example. My current
> workaround with barchart and ugly jags is given.
>
> Any better solution?
>
> Dieter
>
> library(lattice)
> n = 100
> df1 = data.frame(x=0:n,y=((0:n)/n)^2,group="a",age="young")
> df2 = data.frame(x=0:n,y=1-df1$y,group="b",age="young")
> df3 = data.frame(x=0:n,y=((0:n)/n)^3,group="a",age="old")
> df4 = data.frame(x=0:n,y=1-df3$y,group="b",age="old")
> df = rbind(df1,df2,df3,df4)
>
> barchart(y~x|age,groups=group,
> data=df,horizontal=FALSE,stack=TRUE,box.width=1,
>   lwd=0,lty=0, ylim=c(0,1),scales=list(x=list(at=seq(0,n,n/10)) ))

With a restructuring of the data:

df1 = data.frame(x=0:n, y1=((0:n)/n)^2, y2=1-((0:n)/n)^2, age="young")
df2 = data.frame(x=0:n, y1=((0:n)/n)^3, y2=1-((0:n)/n)^3, age="old")
df = rbind(df1, df2)

xyplot((y1+y2) + y1 ~ x | age, data=df, type = "l")

xyplot((y1+y2) + y1 ~ x | age, data=df, type = "l",
       scales = list(axs = "i"),
       panel = panel.superpose,
       panel.groups = function(x, y, fill, ...) {
           panel.polygon(c(min(x), x, max(x)), c(0, y, 0), fill = fill)
       })

-Deepayan



More information about the R-help mailing list