本文介绍了为什么R中的多边形适用于全曲线而不适用于半曲线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么polygon()在两条曲线( 底部图片 )上都能很好地工作,但是在同一条曲线的一半上却不能正确工作( 顶部图片 )?

I'm wondering why polygon() works very well with a two-sided curve (bottom picture), but not working correctly with a half of that same curve (top picture)?

我希望能得到一个简短的解释.

I appreciate a short explanation.

par(mfrow = c(2, 1))

gg = curve(dnorm(x), -4, 0) # Not working!
polygon(gg, col = 2)

gg = curve(dnorm(x), -4, 4) # Working!
polygon(gg, col = 2)

推荐答案

一个curve

由于polygon连接曲线的起点和终点,因此会产生一些奇怪的形状.从?polygon我们可以看到

One curve

Since polygon connects the start and the end of your curve, it creates some weird shape. From ?polygon we can see that

第一个和最后一个点由curve中的fromto值给出.在第一种情况下,它们是-40.

The first and last points are given by the from and to values in curve. In your first case these are -4 and 0.

只需将xlimxaxs = "i"添加到curve()

gg = curve(dnorm(x), -4, 4, xlim = c(-4,0), xaxs = "i") # Working!
polygon(gg, col = 2)

当您想在一条图中放置多条曲线时,可能会遇到无法限制轴的问题,如上所示.因此,我们必须更深入地研究曲线对象的结构(此处为gg).

When you want to put multiple curves in one plot, you might face the problem that you can't limit your axes as shown above. Thus, we have to dig deeper into the structure of a curve object (here gg).

首先创建两条曲线.

gg = curve(dnorm(x), -4, 4) ; 
polygon(gg, col = 2) ; 
gg = curve(dnorm(x), -4, 0, xlim = c(-4,0), xaxs = "i", add = T) ; 

现在,我们来看看gg:

gg 
# $x
# [1] -4.00 -3.96 -3.92 -3.88 -3.84 -3.80 -3.76 -3.72 -3.68 -3.64 -3.60 -3.56 -3.52 -3.48 -3.44 -3.40 -3.36 -3.32 -3.28
# [20] -3.24 -3.20 -3.16 -3.12 -3.08 -3.04 -3.00 -2.96 -2.92 -2.88 -2.84 -2.80 -2.76 -2.72 -2.68 -2.64 -2.60 -2.56 -2.52
#  .....
# $y
# [1] 0.0001338302 0.0001569256 0.0001837125 0.0002147280 0.0002505784 0.0002919469 0.0003396012 0.0003944025 0.0004573148
# [10] 0.0005294147 0.0006119019 0.0007061107 0.0008135212 0.0009357722 0.0010746733 0.0012322192 0.0014106023 0.0016122275
#  .....

我们看到gg只是$x$y坐标的列表.因此,我们可以将0, 0处的一个坐标添加到第二个gg中,以模拟重叠的第二条曲线的末端.然后,正确绘制了两条曲线.

We see that gg is just a list of $x and $y coordinates. Thus, we can add one coordinate at 0, 0 to the second gg to simulate the end of the overlapping second curve. Afterwards both curves are plotted correctly.

gg$x <- c(gg$x, 0)
gg$y <- c(gg$y, 0)
polygon(gg, col = 4)

这篇关于为什么R中的多边形适用于全曲线而不适用于半曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 03:32