Search code examples
rggplot2facet

Change y axis limits for each row of a facet plot in ggplot2


I have a 3 rows by 5 columns facet plot. Each row show data which spread over different ranges. To properly display my data so everything is shown, I don't set a y axis limit.

Here's my code:

require(reshape2)
library(ggplot2)
library(RColorBrewer)

fileName = paste("./data_test.csv", sep = "")

## data available here: https://dl.dropboxusercontent.com/u/73950/data_test.csv

mydata = read.csv(fileName,sep=",", header=TRUE)

dataM = melt(mydata,c("id"))
dataM = cbind(dataM,
            colsplit(dataM$variable,
                     pattern = "_",
                     names = c("Network_model", "order", "category")))
dataM$variable <- NULL
dataM <- dcast(dataM, ... ~ category, value.var = "value")
dataM$minCut <- NULL
dataM$nbr_communities <- NULL
dataM$mean_community_size <- NULL
dataM$density <- NULL

my_palette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))

dataM = melt(dataM, id.vars = c("Network_model", "order", "nodesRemoved", "id"))

my_palette = c(brewer.pal(5, "Blues")[c(4)], brewer.pal(5, "Set1")[c(3)])

ggplot(dataM, aes(x= nodesRemoved ,y= value, group= order, color= order)) +
  geom_point(size = .6,alpha = .15,position="jitter") +  ## increased size
  stat_smooth(se = FALSE, size = .5, alpha = .1, method = "loess") +
  scale_color_manual(values=my_palette) +
  theme_bw() +
  theme(plot.background = element_blank(),
        axis.line = element_blank(),
        legend.key = element_blank(),
        legend.title = element_blank(),
        axis.text.x = element_text(size = 8),
        axis.text.y = element_text(size = 8)
        ) +
  scale_y_continuous("Value") + 
  scale_x_continuous("Time", limits=c(0, 100)) +

  facet_grid(variable ~ Network_model,scales="free")

Which produces this:

enter image description here

Now, I'd like to selectively set limits for each of the three rows, so that the first row is limits=c(1.9, 3), the second is limits=c(0, 1) and the third is limits=c(.3, .7).

How can I achieve this in ggplot2 of faceting?


Solution

  • I think your best option will be to trim the data before plotting it, e.g. with dplyr,

    library(dplyr)
    limits <- data.frame(variable = levels(dataM$variable),
                         min = c(1.9,0,0.3),
                         max = c(3,1,0.7))
    dataC <- inner_join(dataM, limits) %>% filter(value > min, value < max)
    
    last_plot() %+% dataC
    

    enter image description here

    (I initially made the points bigger to see the culprits more clearly)