-----Oorspronkelijk bericht-----
Van: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
Namens Iain Gallagher
Verzonden: dinsdag 8 november 2011 12:51
Aan: r-help
Onderwerp: [R] ggplot2 reorder factors for faceting
Dear List
I am trying to draw a heatmap using ggplot2. In this heatmap I have faceted my
data by 'infection' of which I have four. These four infections break down into
two types and I would like to reorder the 'infection' column of my data to reflect
this.
Toy example below:
library(ggplot2)
# test data for ggplot reordering
genes <- (rep (c(rep('a',4), rep('b',4), rep('c',4), rep('d',4), rep('e',4), rep('f',4)) ,4))
fcData <- rnorm(96) times <- rep(rep(c(2,6,24,48),6),4) infection <- c(rep('InfA',
24), rep('InfB', 24), rep('InfC', 24), rep('InfD', 24)) infType <- c(rep('M', 24),
rep('D',24), rep('M', 24), rep('D', 24))
# data is long format for ggplot2
plotData <- as.data.frame(cbind(genes, as.numeric(fcData), as.numeric(times),
infection, infType))
hp2 <- ggplot(plotData, aes(factor(times), genes)) + geom_tile(aes(fill =
scale(as.numeric(fcData)))) + facet_wrap(~infection, ncol=4)
# set scale
hp2 <- hp2 + scale_fill_gradient2(name=NULL, low="#0571B0", mid="#F7F7F7",
high="#CA0020", midpoint=0, breaks=NULL, labels=NULL, limits=NULL,
trans="identity")
# set up text (size, colour etc etc)
hp2 <- hp2 + labs(x = "Time", y = "") + scale_y_discrete(expand = c(0, 0)) +
opts(axis.ticks = theme_blank(), axis.text.x = theme_text(size = 10, angle = 360,
hjust = 0, colour = "grey25"), axis.text.y = theme_text(size=10, colour =
'gray25'))
hp2 <- hp2 + theme_bw()
In the resulting plot I would like infections infA and infC plotted next to each
other and likewise for infB and infD. I have a column in the data - infType - which
I could use to reorder the infection column but so far I have no luck getting this
to work.
Could someone give me a pointer to the best way to reorder the infection factor
and accompanying data into the order I would like?
Best
iain