このblogの例に従って、次のように進めます。
我々は、2本の線が交差する各点で塗りつぶし色を変更するために
x1 <- c(1, 2, 3, 4, 5, 6)
y1 <- c(1, 10, 15, 7, 12, 3)
y2 <- c(5, 10, 14, 12, 2, 11)
toyset <- as.data.frame(cbind(x1, y1, y2))
(微調整)初期玩具データセットを使用して、我々は、交点を計算します。
toyset$slope1 <- c(NA, with(toyset, diff(y1)/diff(x1)))
toyset$slope2 <- c(NA, with(toyset, diff(y2)/diff(x1)))
toyset$intcpt1 <- with(toyset, y1 - slope1 * x1)
toyset$intcpt2 <- with(toyset, y2 - slope2 * x1)
toyset$x2 <- with(toyset, (intcpt1 - intcpt2)/(slope2 - slope1))
toyset$y3 <- with(toyset, slope1 * x2 + intcpt1)
toyset <- toyset[, c(-4:-7)]
我々は、視覚的に交点の位置を確認することができ、計算が正しいことを確認するには、次の
ggplot(toyset) + geom_line(aes(x1, y1), colour = "red") +
geom_line(aes(x1, y2), colour = "darkgreen") +
geom_point(aes(x2, y3), colour = "darkblue", size = 3)
我々はgeom_ribbon
を使用するように、交差点のポイントを提示することも必要geom_ribbon(x, ymin, ymax)
によって予期される形式で - y3
の単純なコピーがこれを実行します。
toyset$y4 <- toyset$y3
追加のエラーチェックを行い、各データポイントに適切な間隔を割り当てます。 ggplot2
について
toyset[which(toyset$x2 > toyset$x1), c("x2", "y3", "y4")] <- NA
toyset$segment <- findInterval(toyset$x1,
c(min(toyset$x2, na.rm = TRUE),
toyset$x2[which(!is.na(toyset$x2))]))
線の各交差点で塗りつぶしの色を変化させることができるためには、各着色領域の始点と終点を知る必要があります。つまり、交差点の中点は、異なる色で塗りつぶされた2つの隣接するエリアの一部であるため、複製する必要があります。
toyset$x3 <- c(tail(toyset$x2, -1), NA)
toyset$y5 <- c(tail(toyset$y3, -1), NA)
toyset$y6 <- toyset$y5
ここで、2つのラインの座標とカラー領域の開始点と終了点を、長いフォーマットの1つのdata.frameに結合する必要があります。
toyset1 <- toyset[, c(1:3, 7)]
toyset2 <- toyset[!is.na(toyset$x2), c(4:6, 7)]
toyset3 <- toyset[!is.na(toyset$x3), c(8:10, 7)]
names(toyset2) <- names(toyset1)
names(toyset3) <- names(toyset1)
combo <- rbind(toyset1, toyset2)
combo <- rbind(combo, toyset3)
combo <- combo[is.finite(combo$y1), ]
combo <- combo[order(combo$x1), ]
これでセグメントを適切に入力できるようになりました。
ggplot(combo, aes(x1, ymin = y1, ymax = y2))+
geom_ribbon(aes(fill = factor(segment%%2)), alpha = 0.5) +
geom_path(aes(y = y1), colour = "red", size = 1) +
geom_path(aes(y = y2), colour = "darkgreen", size = 1) +
scale_fill_manual(values = c("red", "green"))
Segments filled
私はあなたが、あなたが 'geom_polygon(データ= poly_df、AES(Xを使用することができ、最初の5つの多角形のそれぞれの座標を定義し、各ポリゴンにIDと色を割り当てる必要が推測= x、y = y、塗りつぶし= id、色= id)) ' – beetroot
私はすでにpoly_dfを作成していませんか? – PvGelder
私はそうは思わない。また、両方の線が交差する点を含める必要があります。 – beetroot