代码之家  ›  专栏  ›  技术社区  ›  Dan

平面网格中的自由色阶

  •  2
  • Dan  · 技术社区  · 6 年前

    假设我有以下数据框:

    # Set seed for RNG
    set.seed(33550336)
    
    # Create toy data frame
    loc_x <- c(a = 1, b = 2, c = 3)
    loc_y <- c(a = 3, b = 2, c = 1)
    scaling <- c(temp = 100, sal = 10, chl = 1) 
    
    df <- expand.grid(loc_name = letters[1:3], 
                      variables = c("temp", "sal", "chl"), 
                      season = c("spring", "autumn")) %>% 
      mutate(loc_x = loc_x[loc_name],
             loc_y = loc_y[loc_name],
             value = runif(nrow(.)),
             value = value * scaling[variables])
    

    看起来,

    # > head(df)
    #   loc_name variables season loc_x loc_y     value
    # 1        a      temp spring     1     3 86.364697
    # 2        b      temp spring     2     2 35.222573
    # 3        c      temp spring     3     1 52.574082
    # 4        a       sal spring     1     3  0.667227
    # 5        b       sal spring     2     2  3.751383
    # 6        c       sal spring     3     1  9.197086
    

    我想使用 variables season 要定义面板,如下所示:

    g <- ggplot(df) + geom_point(aes(x = loc_name, y = value), size = 5)
    g <- g + facet_grid(variables ~ season) 
    g
    

    enter image description here

    正如你所看到的,不同 变量 scales = "free" 要解释这一点。

    g <- ggplot(df) + geom_point(aes(x = loc_name, y = value), size = 5)
    g <- g + facet_grid(variables ~ season, scales = "free") 
    g
    

    enter image description here

    非常方便。现在,假设我想这样做,但是用 loc_x loc_y 而且 value 由颜色而不是y位置表示:

    g <- ggplot(df) + geom_point(aes(x = loc_x, y = loc_y, colour = value), 
                                 size = 5)
    g <- g + facet_grid(variables ~ season, scales = "free") 
    g <- g + scale_colour_gradient2(low = "#3366CC", 
                                    mid = "white", 
                                    high = "#FF3300", 
                                    midpoint = 50) 
    g
    

    enter image description here

    请注意 颜色 比例尺不是自由的,与第一个数字一样,比例尺的值是 sal chl 不容易阅读。

    我的问题是:有没有可能做一个相当于 scales=“免费” 但是对于颜色,那么每一行(在本例中)都有一个单独的颜色栏?或者,我是否必须绘制每个变量(即图中的行)并使用以下方式将它们拼接在一起 cowplot ?

    1 回复  |  直到 6 年前
        1
  •  12
  •   Axeman    6 年前

    dplyr :

    library(dplyr)
    library(purrr)
    library(ggplot2)
    library(cowplot)
    
    df %>% 
      group_split(variables, season) %>% 
      map(
        ~ggplot(., aes(loc_x, loc_y, color = value)) + 
          geom_point(size = 5) +
          scale_colour_gradient2(
            low = "#3366CC", 
            mid = "white", 
            high = "#FF3300", 
            midpoint = median(.$value)
          ) +
          facet_grid(~ variables + season, labeller = function(x) label_value(x, multi_line = FALSE))
      ) %>% 
      plot_grid(plotlist = ., align = 'hv', ncol = 2)
    

    enter image description here