R ggplot scale_fill_manual 对范围内的值使用颜色

R ggplot scale_fill_manual using colors for values within a range

我只是希望清理我的代码并学习一两件事。我觉得我让这件事变得比它应该做的更难了。我有一系列 0-9 的数据,我想为该范围内的值指定一种颜色。例如:

0-3 green
4-6 yellow
7-9 red

这是我能够让它发挥作用的唯一方法。我觉得应该有一种方法可以指定休息时间的范围。即 0-3 = 绿色等

ggplot() +
  geom_raster(data = data, aes(x = samples, y = organism, fill = as.factor(value))) +
  scale_fill_manual(values=c("green", "green", "green","green", "yellow","yellow","yellow", "red","red", "red"), breaks=c(0,1,2,3,4,5,6,7,8,9))

以下代码工作正常,但每当我尝试在中断内创建范围时,我都会收到错误消息:

breaks=c(0-3,4-6,7-9)
Error: Insufficient values in manual scale. 10 needed but only 3 provided.

我希望这是不言自明的。如果需要,我可以提供示例数据集(如下)。感谢您的宝贵时间!

samples,organism,value
a,z,0
b,z,1
c,z,2
d,z,3
e,z,4
f,z,5
g,z,6
h,z,7
i,z,8
j,z,9

我没有你的数据,但我做了一些我认为看起来像你的数据:

set.seed(123)
data <- expand.grid(samples = 1:5, organism = LETTERS[1:4])
data$value <- sample(0:9, 20, replace = TRUE)

根据这些数据,我得到了一个不同的错误运行你的代码:

ggplot() +
  geom_raster(data = data, aes(x = samples, y = organism, fill = value)) +
  scale_fill_manual(values=c("green", "green", "green", "green", "yellow", "yellow", "yellow", "red", "red", "red"), 
                    breaks=c(0,1,2,3,4,5,6,7,8,9))
Error: Continuous value supplied to discrete scale

如果我将 value 转换为一个因子,我不会出错。我需要你的数据来帮助诊断错误。

ggplot() +
  geom_raster(data = data, aes(x = samples, y = organism, fill = factor(value))) +
  scale_fill_manual(values=c("green", "green", "green", "green", "yellow", "yellow", "yellow", "red", "red", "red"), 
                    breaks=c(0,1,2,3,4,5,6,7,8,9))

使用我的数据,这是一个更简单的方法(特别是如果 value 是连续的):

ggplot() +
  geom_raster(data = data, aes(x = samples, y = organism, 
                               fill = cut(value, breaks = c(0, 3, 6, 9)))) +
  scale_fill_manual(name = "value", 
                    values = c("green", "yellow", "red"),
                    labels = c("0-3", "4-6", "7-9"))