How to control ylim for a faceted plot with different scales in ggplot2?

后端 未结 3 1432
执笔经年
执笔经年 2021-01-01 11:41

In the following example, how do I set separate ylims for each of my facets?

qplot(x, value,  data=df, geom=c(\"smooth\")) + facet_grid(variable ~ ., scale=\         


        
相关标签:
3条回答
  • 2021-01-01 12:07

    This was brought up on the ggplot2 mailing list a short while ago. What you are asking for is currently not possible but I think it is in progress.

    0 讨论(0)
  • 2021-01-01 12:08

    There are actually two packages that solve that problem now: https://github.com/zeehio/facetscales, and https://github.com/teunbrand/ggh4x. I would recommend using ggh4x because it has very useful tools, such as facet grid multiple layers (having 2 variables defining the rows or columns), scaling the x and y-axis as you wish in each facet, and also having multiple fill and colour scales. For your problems the solution would be like this:

    library(ggh4x)
    
    scales <- list(
      # Here you have to specify all the scales, one for each facet row in your case
      scale_y_continuous(limits = c(2,10),
      scale_y_continuous(breaks = c(3, 4))
    )
    qplot(x, value,  data=df, geom=c("smooth")) +
     facet_grid(variable ~ ., scale="free_y") +
     facetted_pos_scales(y = scales)
    
    0 讨论(0)
  • 2021-01-01 12:09

    As far as I know this has not been implemented in ggplot2, yet. However a workaround - that will give you ylims that exceed what ggplot provides automatically - is to add "artificial data". To reduce the ylims simply remove the data you don't want plot (see at the and for an example).

    Here is an example:

    Let's just set up some dummy data that you want to plot

    df <- data.frame(x=rep(seq(1,2,.1),4),f1=factor(rep(c("a","b"),each=22)),f2=factor(rep(c("x","y"),22)))
    df <- within(df,y <- x^2)
    

    Which we could plot using line graphs

    p <- ggplot(df,aes(x,y))+geom_line()+facet_grid(f1~f2,scales="free_y")
    print(p)
    

    Assume we want to let y start at -10 in first row and 0 in the second row, so we add a point at (0,-10) to the upper left plot and at (0,0) ot the lower left plot:

    ylim <- data.frame(x=rep(0,2),y=c(-10,0),f1=factor(c("a","b")),f2=factor(c("x","y")))
    dfy <- rbind(df,ylim)
    

    Now by limiting the x-scale between 1 and 2 those added points are not plotted (a warning is given):

    p <- ggplot(dfy,aes(x,y))+geom_line()+facet_grid(f1~f2,scales="free_y")+xlim(c(1,2))
    print(p)
    

    Same would work for extending the margin above by adding points with higher y values at x values that lie outside the range of xlim.

    This will not work if you want to reduce the ylim, in which case subsetting your data would be a solution, for example to limit the upper row between -10 and 1.5 you could use:

    p <- ggplot(dfy,aes(x,y))+geom_line(subset=.(y < 1.5 | f1 != "a"))+facet_grid(f1~f2,scales="free_y")+xlim(c(1,2))
    print(p)
    
    0 讨论(0)
提交回复
热议问题