繁体   English   中英

使用 scale_fill_gradientn 将特定颜色分配给条形 plot 中的确定值

[英]Assign specific color to definite value in bar plot using scale_fill_gradientn

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

问题是,我想给一个确定的值(例如 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 应该是白色的

因此,简单的选择是将等于 20 秒的IP重新编码为NA并在该比例下设置一个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()

在此处输入图像描述

如果你想要困难的选项,你必须编写一个调色板 function ,它适用于 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
  }
}

现在你可以像这样 plot :

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()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM