Setting no value to 0 when plotting a stacked area chart

13 views
Skip to first unread message

Etienne B. Racine

unread,
Jun 9, 2009, 8:47:41 AM6/9/09
to ggplot2
When I plot a stacked area chart, I get some holes and the areas are
misordered because some lines are missing. Instead of 0 values, there
is simply no line. How can I tell ggplot to put 0 when there is
nothing ?

Example :

set.seed(1001)
df <- data.frame(
cat = rep(letters[1:4], each = 10),
xax = rep(1:10, 4),
value = floor(rlnorm(40))
)

# this is working great :
qplot(x=xax, y=value, data=df, geom="area", fill = cat,
position="fill")

# but what I really have is looking like that :
df0 <- df[df$value!=0,]
qplot(x=xax, y=value, data=df0, geom="area", fill = cat,
position="fill")

I could generate all the combinations (using expand.grid), but I think
it would make something huge and it wouldn't be very dynamic to
update. Is there another way.

Etienne

Etienne B. Racine

unread,
Jun 9, 2009, 8:53:39 AM6/9/09
to ggplot2
Maybe there is a link with this previous post ?
http://groups.google.com/group/ggplot2/t/eef526d63c59fe9d. But, I
can't get it.

hadley wickham

unread,
Jun 11, 2009, 9:22:22 PM6/11/09
to Etienne B. Racine, ggplot2

I don't think there is any way for ggplot2 to impute this - you need
to know the set of all x values, and what blank values should be
filled in with. It's not too hard to write a function that does this:

allx <- unique(df0$x)

df2 <- ddply(df0, c("cat"), function(df) {
newx <- data.frame(xax = setdiff(allx , df$x), value = 0)
rbind(df[c("xax", "value")], newx)
})

qplot(x=xax, y=value, data=df2, geom="area", fill = cat, position="fill")

Hadley

--
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages