затенение на графике кривой ху в R - PullRequest
1 голос
/ 26 февраля 2012

У меня есть данные, подобные следующим:

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)

Я хочу заштриховать другой цвет внутри кривой. Обратите внимание на границы цветовой заливки в х

region 1 = 1 to 6
 region 2 =  6 to 16
 region 3 =  16 to 20 

enter image description here

Ответы [ 3 ]

5 голосов
/ 26 февраля 2012

Просто продемонстрируйте раздел 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")

enter image description here

4 голосов
/ 26 февраля 2012

Вот решение с 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")

ggplot2 geom_area

2 голосов
/ 26 февраля 2012

Основано на ответе Гонг-И, хотя мне нужно изменить данные, чтобы заполнить нижний многоугольник.Полный ответ таков:

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")

enter image description here

...