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

在ggplot2中为同一变量创建两个连续的颜色渐变比例

  •  0
  • accibio  · 技术社区  · 4 月前

    我有一个包含两个变量的数据帧 Type Time ,我试图将这些值可视化 Value 列使用 geom_tile 瓷砖当前根据连续的颜色梯度着色,从红色(表示高值)到白色(表示低值)。但是,我想为 类型 变量基于 Category 它属于。具体来说,我想为 BB 类别和红白渐变(红色表示高值) SS 类别。

    以下是我迄今为止所尝试的:

    library(ggplot)
    
    
    df <- data.frame(Type = c(rep("A", 5), rep("B", 5), rep("C", 5)),
                     Time = rep(1:5, 3),
                     Value = round(runif(15, min = -3, max = 3), 2),
                     Category = c(rep("BB", 5), rep("SS", 10)))
    
    
    ggplot(data = df, 
       aes(x = Time, 
           y = Type, 
           fill = Value)) + 
    geom_tile(height = 0.8, 
                width = 1) +
      scale_fill_gradient2(limits = c(-3, 3), 
                           breaks = c(-3, 0, 3),
                           low = "white",
                           mid = "mistyrose",
                           high = "#A63446",
                           midpoint = 0,
                           guide = guide_colorbar(frame.colour = "black", 
                                                  ticks.colour = "black")) +
      theme_bw()
    

    enter image description here

    1 回复  |  直到 4 月前
        1
  •  1
  •   stefan    4 月前

    使用 ggnewscale 该包装允许为同一美学设计多个刻度:

    library(ggplot2)
    library(ggnewscale)
    
    ggplot(
      data = df,
      aes(
        x = Time,
        y = Type,
        fill = Value
      )
    ) +
      geom_tile(
        data = ~subset(.x, Category == "SS"),
        height = 0.8,
        width = 1
      ) +
      scale_fill_gradient2(
        limits = c(-3, 3),
        breaks = c(-3, 0, 3),
        low = "white",
        mid = "mistyrose",
        high = "#A63446",
        midpoint = 0,
        guide = guide_colorbar(
          frame.colour = "black",
          ticks.colour = "black"
        ),
        name = "SS"
      ) +
      ggnewscale::new_scale_fill() +
      geom_tile(
        data = ~subset(.x, Category == "BB"),
        aes(
          x = Time,
          y = Type,
          fill = Value
        ),
        height = 0.8,
        width = 1
      ) +
      scale_fill_gradient(
        limits = c(-3, 3),
        breaks = c(-3, 0, 3),
        low = "white",
        high = "navy",
        guide = guide_colorbar(
          frame.colour = "black",
          ticks.colour = "black"
        ),
        name = "BB"
      ) +
      theme_bw() +
      theme(
        legend.box = "horizontal"
      )
    

    enter image description here