sort fill data within geom_tile

1,988 views
Skip to first unread message

Brenna Forester

unread,
Nov 28, 2014, 12:41:04 PM11/28/14
to ggp...@googlegroups.com
Hello everyone,

I'm relatively new to ggplot2. I have looked around online & in my copy of R Graphics Cookbook and can't seem to find a solution to my problem - any thoughts would be appreciated!

I would like to be able to sort my fill data by value (0 -> 1) based on the x axis (meaning that the y axis will get shuffled around). Here is a reproducible example:

# Create data:

x <- as.factor(c("A","B","C","D","E"))
y <- as.factor(c(1:20))
z <- runif(100, min=0, max=1)

dat <- cbind.data.frame(rep(x,20), sort(rep(y,5)), z)
colnames(dat) <- c("x","y","z")

# Plot data:

p <- ggplot(dat, aes(x=x, y=y, fill=z)) + geom_tile()
p + scale_fill_gradientn(colours=c("black","white"))



You will see that, of course, the layout of the plot is based on the factor ordering of x and y. I would like to sort the data based on, for example, the value of z in "A" on the x-axis (that is, sort the y-axis based on z values within "A" from 0 -> 1).

Thank you!
Brenna


Dennis Murphy

unread,
Nov 28, 2014, 4:38:35 PM11/28/14
to Brenna Forester, ggplot2
If you sort the data by z within levels of x and define a new
'ordered' y variable prior to the ggplot() call, you can get what I
believe you want:

library(plyr)
dat2 <- arrange(dat1, x, z)
dat2$y1 <- factor(seq(20))

ggplot(dat2, aes(x = x, y = y1, fill = z)) + geom_tile() +
scale_fill_gradientn(colours = c("black", "white"))


Dennis
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> ---
> You received this message because you are subscribed to the Google Groups
> "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Brenna Forester

unread,
Nov 28, 2014, 5:29:40 PM11/28/14
to ggp...@googlegroups.com, brenna....@gmail.com
Thank you Dennis, for your quick reply! I did not know about "arrange" in plyr...that is very handy!

I need to keep the original y values because they correspond across x's. That's why I'd only sort across one value of x (because the rest of the x's won't sort on their fill values from 0 -> 1, but will instead follow whatever ordering of y is dictated by that x).

If it helps in understanding what I need to do and why, basically I'm trying to see which molecular markers (on the y axis) are well vs poorly represented across populations (x axis). That's why I need the y's to be maintained in the data.

Brenna
Reply all
Reply to author
Forward
0 new messages