gpt4 book ai didi

r - 用 R 中的 ggplot2 填充两行之间的区域

转载 作者:行者123 更新时间:2023-12-04 18:43:31 25 4
gpt4 key购买 nike

这是一个玩具数据集:

xa <- c(4, 5, 4.5, 4, 3, 1.5)
ya <- c(1, 2, 4, 5, 5.5, 6)
xb <- c(3.8, 4.5, 4, 3.5, 2.5, 1)
yb <- c(1, 2, 3, 4, 5, 5.8)
toyset <- as.data.frame(cbind(xa, ya, xb, yb))

如果我们简单地绘制连接它们的点和线,我们得到:
library(ggplot2)
ggplot(toyset) + geom_path(aes(xa, ya)) + geom_path(aes(xb, yb)) +
geom_point(aes(xa, ya)) + geom_point(aes(xb, yb))

enter image description here

中是否有简单的方法? ggplot2 填充由两条线定义的区域?

最佳答案

您可以使用 geom_polygon :

poly_df <- rbind(setNames(toyset[,1:2],c('x','y')),
setNames(toyset[6:1,3:4],c('x','y')))

ggplot(toyset) +
geom_path(aes(xa, ya)) +
geom_path(aes(xb, yb)) +
geom_point(aes(xa, ya)) +
geom_point(aes(xb, yb)) +
geom_polygon(data = poly_df,aes(x = x,y = y),fill = "lightblue",alpha = 0.25)

我修复了您的示例数据 (54) 中的错字。请注意,您必须非常注意多边形数据框中点的排序。这与 geom_path 的交易相同.

关于r - 用 R 中的 ggplot2 填充两行之间的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19387202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com