用R中的ggplot2填充两行之间的区域 [英] Fill the region between two lines with ggplot2 in R

查看:235
本文介绍了用R中的ggplot2填充两行之间的区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个玩具数据集:

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

如果我们简单地画出连接它们的点和线,我们可以得到:

<$ p $ (aes(xa,ya))+ geom_path(aes(xb,yb))+
geom_point(aes(xa,ya) ,ya))+ geom_point(aes(xb,yb))

ggplot2

中有一种简单的方法:

strong>来填充由这两行定义的区域?

解决方案

您可以使用 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 = poly_df,aes(x = x,y = y),fill =lightblue,alpha = 0.25)

我修正了您的样本数据中的错字(54)。请注意,您必须非常小心多边形数据框中点的排序。与 geom_path 相同。


This is a toy dataset:

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

If we simply plot the points and lines connecting them we get:

library(ggplot2)
ggplot(toyset) + geom_path(aes(xa, ya)) + geom_path(aes(xb, yb)) +
  geom_point(aes(xa, ya)) + geom_point(aes(xb, yb))

Is there a simple way in ggplot2 to fill the region defined by the two lines?

解决方案

You can use 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)

I fixed the typo in your sample data (54). Note that you have to be very careful about the ordering of the points in the data frame for the polygon. It's the same deal as with geom_path.

这篇关于用R中的ggplot2填充两行之间的区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆