在 R 中有条件地填充 ggplot 的背景

use*_*544 3 r ggplot2

我想R用特定的颜色填充 ggplot 的背景。

数据帧包含3列:timevalue,和color

df <- data.frame(time = seq(1, 100, 1), 
                 value = c(runif(n = 45, min = 1, max= 10), runif(10, 40, 50), runif(45, 70, 90)), 
                 color = c(rep("green", 45), rep("orange", 10), rep("red", 45))) 
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式填充情节的背景:

library(tidyverse)

ggplot(df) + 
  geom_line(aes(x = time, y = value)) + 
  annotate("rect", xmin=-Inf, xmax= 45, ymin = -Inf, ymax = Inf, alpha = 0.2, fill = "green") +
  annotate("rect", xmin=45, xmax= 55, ymin = -Inf, ymax = Inf, alpha = 0.2, fill = "orange") +
  annotate("rect", xmin=55, xmax= Inf, ymin = -Inf, ymax = Inf, alpha = 0.2, fill = "red") 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在上面的例子中,背景fill是“硬编码”的。有没有更方便的/自动化的方式来发现xminxmax颜色转换之间的边界值?

zig*_*tar 5

您可以将平铺图分层后仅一行,并用于cut为每个点分配一种颜色。

对于您的数据,我可以使用一个简单的cut. 但我怀疑它是否总是像示例数据一样好:

ggplot(df) + 
  geom_tile(aes(x=time,y=50,fill=cut(value,3)),height=100,alpha=0.2) + 
  geom_line(aes(x=time,y=value))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

编辑:我想念你的数据中已经有了颜色

然后就更简单了:

ggplot(df) + 
  geom_tile(aes(x=time,y=50,fill=color),height=100,alpha=0.2) + 
  geom_line(aes(x=time,y=value)) + 
  scale_fill_manual("Important aspect", values=c("green","orange","red"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明