我想用ggplot将对角线上方的区域着色为红色,将其下方的区域着色为绿色。我已经通读了 geom_ribbon,但据我所知,我只能指定 y 值。有人可以支持吗?非常感谢。
# Test data
df <- data.frame(
x = sample(1:100, 100, replace=FALSE),
y = sample(1:100, 100, replace=FALSE))
library(ggplot2)
g <- ggplot(data=df, aes(x=x, y=y))
g +
geom_point() +
geom_abline(intercept = 0, slope = 1)
# + geom_ribbon(aes(ymin=2 , ymax=50), fill="red", alpha=0.2) not working
Run Code Online (Sandbox Code Playgroud)
geom_polygon可用于对上、下三角形区域进行着色。
# Test data
df <- data.frame(
x = sample(1:100, 100, replace=FALSE),
y = sample(1:100, 100, replace=FALSE))
# Coordinates of the upper and lower areas
trsup <- data.frame(x=c(0,0,100),y=c(0,100,100))
trinf <- data.frame(x=c(0,100,100),y=c(0,0,100))
library(ggplot2)
# Use geom_polygon for coloring the two areas
g <- ggplot(data=df, aes(x=x, y=y))
g + geom_point() +
geom_abline(intercept = 0, slope = 1) +
geom_polygon(aes(x=x, y=y), data=trsup, fill="#FF000066") +
geom_polygon(aes(x=x, y=y), data=trinf, fill="#00FF0066")
Run Code Online (Sandbox Code Playgroud)