我想R用特定的颜色填充 ggplot 的背景。
数据帧包含3列:time,value,和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是“硬编码”的。有没有更方便的/自动化的方式来发现xmin和xmax颜色转换之间的边界值?
您可以将平铺图分层后仅一行,并用于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)