geom_tile:如果满足特定条件,则显示图块颜色

Posted

技术标签:

【中文标题】geom_tile:如果满足特定条件,则显示图块颜色【英文标题】:geom_tile: show tile color if a specific condition meets 【发布时间】:2021-04-28 23:12:00 【问题描述】:

如果满足特定条件(例如 z > 1),我想显示颜色,否则显示无色。 你能告诉我怎么做吗?

xp <- c('Disease_1','Disease_2','Disease_3','Disease_4')
xp1 <- xp[1:2]
yp <- c('BCell','TCell')
df <- list(x=1:2,y=1:4,xp1,yp)
df <- expand.grid(df)
df$z <- c(1.804344554,1.158037086,1.686173307,
          0.500280283,1.710806067,0.857513435,
          0.66474755,1.164780941,1.769090931,
          2.058400169,3.114233859,1.436684123,
          1.770306398,0.995507604,2.538556363,
          2.264486118,1.424789875,1.816608927,
          2.773082903,1.197434618,0.829416784,
          1.622892741,2.035117094,1.650363345,
          1.927235048,1.546477438,2.308773122,
          1.041881013,1.216029616,0.478353441,
          0.834348006,1.240448774)

cols <- rev(brewer.pal(11, 'RdYlBu'))

p <- ggplot(df)
p <- p + geom_tile(aes(x, y, fill = z), 
                   colour = "black", width=0.85, height=0.85, size=1)+ # define each rectangle (small tile) border (line and size and color)
  facet_grid(Var3~Var4) + 
  theme(strip.background =element_blank(), #remove bg color of facet_grid texts
        strip.text.x = element_text(size=12, color="black", face="bold"), # font of upper texts
        strip.text.y = element_text(size=10, color="black", face="bold")) # font of right texts

【问题讨论】:

请贴出xp[1:2](或xp1,对我们来说可能更容易)和yp的值,这样代码不可重现。 fill = ifelse(condition, z, NA)? xp &lt;- c('Disease_1','Disease_2','Disease_3','Disease_4') yp &lt;- c('BCell','TCell') 【参考方案1】:

如果不满足条件,要使图块无色,请在 ifelse 语句中指定 NA,并在 scale_fill_continuous 中指定颜色 "white"

library(ggplot2)
library(RColorBrewer)

cols <- rev(brewer.pal(11, 'RdYlBu'))
df
p <- ggplot(df)
p <- p + geom_tile(aes(x, y, fill = ifelse(z > 1, z, NA)), 
                   colour = "black", width=0.85, height=0.85, size=1)+ # define each rectangle (small tile) border (line and size and color)
  scale_fill_continuous(name = "z Scale", na.value = 'white') +
  labs() +
  facet_grid(Var3 ~ Var4) + 
  theme(strip.background =element_blank(), #remove bg color of facet_grid texts
        strip.text.x = element_text(size=12, color="black", face="bold"), # font of upper texts
        strip.text.y = element_text(size=10, color="black", face="bold")) # font of right texts
p

【讨论】:

是否也可以在右侧面板中为每个图块显示一次图例名称(每个块都相同)?

以上是关于geom_tile:如果满足特定条件,则显示图块颜色的主要内容,如果未能解决你的问题,请参考以下文章

MySQL存储过程——一一检查是不是满足某些条件;如果不满足,则退出程序并返回特定消息

如果仅在 MongoDB 中满足特定条件,则分组

如果在 Select-Query 中满足特定条件,则创建唯一标识符

如果条件不满足,则“短路”YARP RequestTransform 并返回自定义响应

从表中选择所有或仅特定的行

Swift:如果条件不满足,则继续执行 segue