3

I have experimental data that I want to plot using ggplot's facet_grid.

The experiment collected measurements from two species, three conditions, in 6 batches:

species <- c("spcies1","species2")
conditions <- c("cond1","cond2","cond3")
batches <- 1:6

df <- expand.grid(species=species,condition=conditions,batch=batches)

the measurements are fractions between 0 and 1:

set.seed(1)
df$y <- runif(nrow(df),0,1)

In this case I have only a single replicate from each species, condition, and batch:

df$replicate <- 1

But that is flexible.

I want to color each measurement by its species, condition, and batch (in this specific example since there's a single replicate each observation has its own unique color):

df$col.fill <- paste(df$species,df$condition,df$batch,sep=".")

Factoring the variables:

df$col.fill <- factor(df$col.fill,levels=unique(df$col.fill))
df$species <- factor(df$species,levels=species)
df$condition <- factor(df$condition,levels=conditions)

I want to plot the data such that they're facetted by species, condition, and batch, and the facets are labeled accordingly.

Here's what I'm trying: library(ggplot2)

integerBreaks <- function(n = 5, ...)
{
  library(scales)
  breaker <- pretty_breaks(n, ...)
  function(x){
    breaks <- breaker(x)
    breaks[breaks == floor(breaks)]
  }
}


ggplot(df,aes(x=replicate,y=y,color=col.fill))+
geom_point(size=3)+facet_grid(~species+condition+batch,scales="free_x")+
scale_x_continuous(breaks=integerBreaks())+
theme_minimal()+theme(legend.position="none",axis.title=element_text(size=8))

which gives me: enter image description here

What this does is repeat the species and condition per each batch and so the labels are too crowded and get cut down. Is there a way to have the species facet labels appear only once per each species, and the condition facet labels to appear only once per each condition (i.e., follow their hierarchy)?

This would mean that I'll have only two species facet labels, and six condition facet labels (repeating for each species).

dan
  • 6,048
  • 10
  • 57
  • 125
  • If I'm understanding your question correctly, this is a close relative of [this question](https://stackoverflow.com/questions/36941197/overall-label-for-facets?noredirect=1&lq=1) and [this question](https://stackoverflow.com/questions/11353287/how-do-you-add-a-general-label-to-facets-in-ggplot2), although these questions involve only adding a single overall label across strips (i.e., two facet variables instead of three as in your case). – aosmith Sep 29 '17 at 20:36
  • See the solution posted here, using `grid` and `gtable` to allow for nested facets https://stackoverflow.com/questions/40316169/nested-facets-in-ggplot2-spanning-groups – Djork Sep 29 '17 at 20:45
  • Thanks. Is there a way to relabel facet labels after the plot has been created? – dan Sep 29 '17 at 23:35

0 Answers0