gpt4 book ai didi

r - 如何在R中的某些特定区域填充颜色?

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

这是问题所在:

x<-seq(0,10,length.out = 1000)
y1<-dnorm(x,mean = 2,sd=1)
y2<-dnorm(x,mean = 6,sd=1)
plot(x,y1,type="l")
lines(x,y2)
abline(v=x[380])

该图如下所示。如何在垂直线的每一侧填充 2 种不同的颜色,例如红色和蓝色,但仍低于两个正常密度函数。我以为我可以使用多边形,但失败了。

这是没有填充颜色的图表:

enter image description here

最佳答案

这是一种方法:

首先,我们将获得密度的平行最小值 - 这是顶部的向量 y我们多边形的坐标。

y = pmin(y1, y2)

# set up your plot as in the question
plot(x, y1, type="l")
lines(x, y2)

# define a re-usable variable for the vertical line placement
x_vert = 380
abline(v = x[x_vert])

# Now we'll draw 2 polygons, one for the left side, one for the right.
# The first (x,y) pairs of the polygon are just the (x,y) coords of the
# density we're filling to, until the vertical line
# Then we need to connect the "bottom" points, which have coordinates
# (x[x_vert], 0) and (x[1], 0)
polygon(x = c(x[1:x_vert], x[x_vert], x[1]),
y = c(y[1:x_vert], 0, 0),
col = "blue")
# similar for the right hand polygon, but now going from x_vert to length(x)
polygon(x = c(x[x_vert:length(x)], x[length(x)], x[x_vert]),
y = c(y[x_vert:length(x)], 0, 0),
col = "red")

瞧!

enter image description here

关于r - 如何在R中的某些特定区域填充颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093156/

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