我的数据类似于以下内容:
X <- 1:20
B <- c(1,4,6,3,1, 4, 5,8,8,6,3,2,1, 1,5,7,8,6,4,2)
C <- B + 4
myd <- data.frame (X, B, C)
我希望在曲线内以不同的颜色着色。请注意边界颜色填充x
region 1 = 1 to 6
region 2 = 6 to 16
region 3 = 16 to 20
答案 0 :(得分:5)
只需演示1:6部分:
R> plot(X, B, type="l", col="blue", xlim=c(0, 25), ylim=c(0, 15))
R> par(new=TRUE)
R> plot(X, C, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
R> polygon(c(1:6, 6:1), c(B[1:6], C[6:1]), col="purple")
答案 1 :(得分:4)
这是ggplot2的解决方案。
library(ggplot2)
library(reshape2)
d <- melt(myd, id.vars="X")
d <- rbind(
transform( d[ 0 <= d$X & d$X <= 6, ], interval=1 ),
transform( d[ 6 <= d$X & d$X <= 16, ], interval=2 ),
transform( d[ 16 <= d$X & d$X <= 20, ], interval=3 )
)
# Set the order in which we fill the areas:
# first the large ones ("C"), then the small ones ("B");
# Otherwise, the small ones are invisible.
d$variable <- LETTERS[3-as.numeric(d$variable)] # Alphabetic order
ggplot( d, aes(X,value,fill=paste(variable,interval)) ) +
# Set the alpha to a value close to 1, to see if the order is wrong
geom_area(position="identity", alpha=.9) +
opts(legend.position = "none")
答案 2 :(得分:2)
基于Gong-Yi的回答,虽然我必须修改数据以填充下部多边形。完整的答案如下:
X <- 1:20
B <- c(1,4,6,3,1, 4, 5,8,8,6,3,2,1, 1,5,7,8,6,4,2)
C <- B + 4
A <- rep (0, length(B))
myd <- data.frame (X, B, C, A)
plot(X, B, type="l", col="blue", xlim=c(0, 25), ylim=c(0, 15))
# 1 to 6
par(new=TRUE)
plot(X, C, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
polygon(c(1:6, 6:1), c(B[1:6], C[6:1]), col="green1")
par(new=TRUE)
plot(X, B, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
polygon(c(1:6, 6:1), c(B[1:6], A[6:1]), col="green4")
# 6 to 16
par(new=TRUE)
plot(X, C, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
polygon(c(6:16, 16:6), c(B[6:16], C[16:6]), col="blue1")
par(new=TRUE)
plot(X, B, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
polygon(c(6:16, 16:6), c(B[6:16], A[16:6]), col="blue4")
# 16 to 20
par(new=TRUE)
plot(X, C, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
polygon(c(16:20, 20:16), c(B[16:20], C[20:16]), col="purple1")
par(new=TRUE)
plot(X, B, type="l", col="red", xlim=c(0, 25), ylim=c(0, 15))
polygon(c(16:20, 20:16), c(B[16:20], A[20:16]), col="purple4")