Different y-limits on ggplot facet grid bar graph?

后端 未结 1 1473
悲哀的现实
悲哀的现实 2020-12-18 23:57

My data:

    day variable      value
1  Fri     avg1 446.521127
2  Mon     avg1 461.676056
3  Sat     avg1 393.366197
4  Sun     avg1 435.985714
5  Thu     a         


        
相关标签:
1条回答
  • 2020-12-19 00:08

    You can create separate y-ranges for different facets when using geom_point, but I don't know of a way to do it with geom_bar. To set specific y-ranges with facet_wrap and geom_bar, the only way I know of is to create separate plots and then put them side by side using grid.arrange from the gridExtra package. (Using a vertical scale that doesn't go down to zero will exaggerate differences between points/bars, which can be misleading, but you'll have to decide if it makes sense for your particular case.)

    First, here's the geom_point version: The idea is to create a "dummy" data frame with lower and upper values you want for ylim and then "plot" them using geom_blank. geom_blank doesn't plot anything, but adding this geom will ensure that the axis range is what you want it to be for each facet.

    ddummy = data.frame(day=NA, variable=rep(c("avg1", "avg2"), each=2), 
                   value=c(0.5*max(df$value[df$variable=="avg1"]), 
                           1.1*max(df$value[df$variable=="avg1"]),
                           0.5*max(df$value[df$variable=="avg2"]), 
                           1.1*max(df$value[df$variable=="avg2"])))
    
    g <- ggplot(df, aes(x=day, y=value))
    
    g + geom_point() + 
      geom_blank(data=dummy, aes(day, value)) +
      facet_grid(variable ~ ., scales="free")
    

    enter image description here

    And here are separate plots, put together with grid.arrange:

    avg1 = ggplot(df[df$variable=="avg1",], aes(x=day, y=value)) +
      geom_bar(stat="identity") +
      facet_wrap(~variable) +
      coord_cartesian(ylim=c(300,500))
    
    avg2 = ggplot(df[df$variable=="avg2",], aes(x=day, y=value)) +
      geom_bar(stat="identity") +
      facet_wrap(~variable) +
      coord_cartesian(ylim=c(3.5,8))
    
    gridExtra::grid.arrange(avg1, avg2, ncol=2)
    

    enter image description here

    To use geom_segment (per your comment) you could do this:

    library(dplyr)
    
    ggplot(df %>% group_by(variable) %>%
             mutate(ymin=0.5*max(value))) +
      geom_segment(aes(x=day, xend=day, y=ymin, yend=value), 
                   size=5, colour=hcl(195,100,65)) + 
      facet_grid(variable ~ ., scales="free")
    
    0 讨论(0)
提交回复
热议问题