使用data.frame / tibble在ggplot中指定scale_x_continous中断?

时间:2018-05-01 11:23:51

标签: r ggplot2

我得到了以下情节:

require(tidyverse)
set.seed(123)

vary_1 <- c(
    exp(rnorm(250,5,1)),
    rnorm(250,10,10),
    exp(rnorm(250,20,1)),
    exp(rnorm(250,30,1)))


vary_2 <- c(
    rep('A',250),
    rep('B',250),
    rep('C',250),
    rep('D',250))

data_frame(vary_1,vary_2) %>% 
    ggplot(aes(vary_1,color = vary_2,fill = vary_2))+
    geom_density()+
    facet_wrap(~vary_2,scales = 'free')

我想使用data_frame中的值来指定缩放中断。我得到这样的值:

p <- data_frame(vary_1,vary_2) %>% 
    ggplot(aes(vary_1,color = vary_2,fill = vary_2))+
    geom_density()+
    facet_wrap(~vary_2,scales = 'free')

q <- layer_data(p)
q %>%
    group_by(PANEL) %>%
    summarise_at(vars(x), funs(min, max))

  PANEL   min   max
  <fct> <dbl> <dbl>
1 1      8.53  16.1
2 2      7.55  13.8
3 3      4.50  12.4
4 4      9.53  12.2
5 5     10.0   12.1
6 6      8.12  11.2
7 7      8.19  11.2
8 8      6.46  10.4
9 9      4.41  10.3

我的解决方案是将split q转换为list并使用它来指定中断,但ggplot不喜欢这样,并给出错误。如何使用data_frameggplot facets中指定中断?或者有更好的方法吗?

breaks_ls <- q %>% 
    group_by(PANEL) %>%
    summarise_at(vars(x), funs(min, max)) %>% 
    ungroup() %>% 
    select(PANEL,min,max) %>% 
    split(.,.$PANEL)

break_values <- map(breaks_ls,function(x){
    as.numeric(x[1,])
})


data_frame(vary_1,vary_2) %>% 
    ggplot(aes(vary_1,color = vary_2,fill = vary_2))+
    geom_density()+
    facet_wrap(~vary_2,scales = 'free')+
    scale_x_continuous(breaks = map(breaks_ls,function(x){
        as.numeric(x[1,])
    }))

给出此错误

Error in x[finite & x < range[1]] <- NA_real_ : 
  (list) object cannot be coerced to type 'double'

1 个答案:

答案 0 :(得分:0)

一种方法是使用patchwork package。但这种方法可能更费力。

这种方法的工作原理如下:

  1. 使用df_list制作一个列表split
  2. 使用list2env(df_list, globalenv())
  3. 提取对象并将其存储到全局环境中
  4. 根据需要修改每个图。
  5. 使用patchwork包修补您的地块。
  6. library(patchwork)
    
    df <- data.frame(vary_1, vary_2)
    
    df_list <- df %>% 
      split(.$vary_2) %>%
      map(~ggplot(.,aes(vary_1))+
            geom_density())
    
    list2env(df_list, globalenv())
    
    # I used other values, but you can adjust to your use case
    A <- A + xlim(0, 2000)
    B <- B + xlim(-10, 30)
    C <- C + xlim(0, 2e9)
    D <- D + xlim(0, 1e14)
    
    (A + B) / (C + D)
    

    enter image description here