【问题标题】:Assign specific color to definite value in bar plot using scale_fill_gradientn使用 scale_fill_gradientn 将特定颜色分配给条形图中的确定值
【发布时间】:2019-11-04 17:07:07
【问题描述】:

我有一个庞大的数据集,其中包含 20 名患者的某些参数的每分钟记录。 通过可视化患者监测记录(IP 参数),我试图构建彩色条形图。 所以我在 r 中使用了scale_fill_gradient() 函数。

问题是,我想为一个确定的值(例如 IP = 20)分配一个特殊的颜色(比如说白色)。 是否可以使用 scale_fill_gradient 做到这一点?

我的数据库是这样的:

Patient min IP
1a      75  19
1a      76  21 
1a      77  20
1a      78  18.5
1a      79  17
1a      80  25
1a      81  29.3
1a      82  32.1
1a      83  30.9
2c      1   2
2c      2   5
2c      3   8 
2c      4   9
2c      5   12
2c      6   16   
2c      7   18
3v      72  38 
3v      73  35
3v      74  30.3
3v      75  28.7
3v      76  27
3v      77  25.2
3v      78  22
3v      79  19.1
3v      80  18 
3v      81  15

我的代码是

i<- ggplot(data, aes(patient, IP, fill=IP))
IPcol <- c("green", "greenyellow", "#fed976","#feb24c", "#fd8d3c", "#fc4e2a", "#e31a1c", "#bd0026", "#800026", "black")
i+geom_bar(stat = "identity")+ scale_fill_gradientn(colours = IPcol)+ coord_flip()+scale_y_time()

从此代码中,我获得以下图像:

所以我唯一想改变的是 IP = 20 应该是白色的

【问题讨论】:

    标签: r ggplot2 gradient geom-bar


    【解决方案1】:

    因此,简单的选择是将等于 20 秒的 IPs 重新编码为 NAs 并以该比例设置 na.value

    data <- read.table(text = your_posted_data, header = T)
    
    
    IPcol <- c("green", "greenyellow", "#fed976","#feb24c", "#fd8d3c", 
               "#fc4e2a", "#e31a1c", "#bd0026", "#800026", "black")
    
    ggplot(data, aes(Patient, IP, fill= ifelse(IP != 20, IP, NA))) +
      geom_col() +
      scale_fill_gradientn(colours = IPcol, na.value = "white")+ 
      coord_flip()+
      scale_y_time()
    

    如果您想要较难的选项,则必须编写一个调色板函数,该函数适用于 0-1 范围内的值,并将重新缩放的 20 设置为白色:

    # Define an area to set to white
    target <- (c(19.5, 20.5) - min(data$IP)) / (max(data$IP) - min(data$IP))
    
    # Build a palette function
    my_palette <- function(colours, values = NULL) {
      ramp <- scales::colour_ramp(colours)
      force(values)
      function(x) {
        # Decide what values to replace
        replace <- x > target[1] & x < target[2]
        if (length(x) == 0)
          return(character())
        if (!is.null(values)) {
          xs <- seq(0, 1, length.out = length(values))
          f <- stats::approxfun(values, xs)
          x <- f(x)
        }
        out <- ramp(x)
        # Actually replace values
        out[replace] <- "white"
        out
      }
    }
    

    现在你可以像这样绘制它:

    ggplot(data, aes(Patient, IP, fill= IP)) +
      geom_col() +
      continuous_scale("fill", "my_pal", my_palette(IPcol), 
                       guide = guide_colourbar(nbin = 100))+ 
      coord_flip()+
      scale_y_time()
    

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 1970-01-01
      • 2021-07-08
      • 2013-09-25
      • 2021-10-06
      • 1970-01-01
      • 2014-04-07
      • 2012-10-18
      相关资源
      最近更新 更多