在 R 编程中的核密度图的两点之间添加颜色 - 使用 with()函数
plot()和with()函数用于在 R 语言中的核密度图的两个点的特定区域之间绘制和添加颜色。
绘制核密度图
R语言中的plot()
函数用于绘制核密度图
Syntax: plot(dens_x)
Parameters:
dens_x: Default plot of density.
Returns: Kernel density plot
# Create example data
set.seed(72500)
x <- rnorm(800)
dens_x <- density(x)
plot(dens_x)
输出:
为绘图添加颜色
with()
函数用于在图形的两点之间添加颜色。
Syntax:
with(dens_x,
polygon(x = c(x),
y = c(0, y[x_low:x_high], 0),
col = ” “))
Parameters:
dens_x: Default plot of density.
x_low, x_high: lower limit and upper limit of colored area
col: Name of color
Returns: Color plot between to particular plots with specified color.
# color the plot
set.seed(72500)
x <- rnorm(800)
dens_x <- density(x)
plot(dens_x)
x_low <- min(which(dens_x$x >= - 0.5)) # Define lower limit of colored area
x_high <- max(which(dens_x$x < 1)) # Define upper limit of colored area
with(dens_x, # Add color between two limits
polygon(x = c(x[c(x_low, x_low:x_high, x_high)]),
y = c(0, y[x_low:x_high], 0),
col = "darkgreen"))
输出: