R语言 给ggplot2绘图添加置信区
在这篇文章中,我们将讨论如何在R编程语言中为ggplot2图添加置信带。
置信带是散点图或拟合线图上的线条,描述了数据范围内所有点的上限和下限的置信界限。这可以帮助我们直观地看到无法保证准确值的数据的误差范围。为了在R语言中给散点图添加置信带,我们使用ggplot2包的geom_ribbon函数。
首先,我们将使用ggplot2包的geom_point()函数制作一个基本散点图。
语法
ggplot( dataframe, aes( x, y ) )+ geom_point( )
例子: 这里是一个使用R语言中ggplot2包的ggplot()和geom_point()函数制作的基本散点图。
# create data vectors
xAxis <- 1:200
yAxis <- rnorm(200) + xAxis / 10
# create data frame from above data vectors
sample_data <- data.frame(xAxis, yAxis)
# load library ggplot2
library("ggplot2")
# create ggplot2 scatter plot
ggplot(sample_data, aes(xAxis, yAxis)) +
geom_point()
输出
为了添加置信带,我们还需要两个变量,对于xAxis和yAxis向量的每个数据变量,我们需要一个相应的低值和高值向量来创建置信带的极限。我们可以在geom_ribbon()函数中使用这些值,在散点图点周围创建一个置信带。
语法
plot + geom_ribbon( aes(ymin, ymax) )
参数
- ymin: 决定带的下限
- ymax :决定波段的上限
例子: 这是一个使用R语言中ggplot2包的geom_ribbon()函数绘制的带有置信带的散点图。
# create data vectors
xAxis <- 1:200
yAxis <- rnorm(200) + xAxis / 10
lowBand <- yAxis + rnorm(200, - 1.5, 0.1)
highBand <- yAxis + rnorm(200, + 1.5, 0.1)
# create data frame from above data vectors
sample_data <- data.frame(xAxis, yAxis, lowBand, highBand)
# load library ggplot2
library("ggplot2")
# create ggplot2 scatter plot
ggplot(sample_data, aes(xAxis, yAxis)) +
geom_point()+
# geom_ribbon function is used to add confidence interval
geom_ribbon(aes(ymin = lowBand, ymax = highBand),
alpha = 0.2)
输出
我们可以使用geom_ribbon()函数的颜色、填充和alpha参数来分别改变置信带的轮廓颜色、背景颜色和透明度。这些属性可以单独使用,也可以组合使用,以创建所需的绘图外观和感觉。
语法
plot + geom_ribbon( aes(ymin, ymax), color, fill, alpha )
参数
- color: 决定了轮廓的颜色
- fill: 决定背景的颜色
- alpha: 决定置信带的透明度
例子: 在这里,我们做了一个带有置信带的散点图,用一种颜色来突出显示
# create data vectors
xAxis <- 1:200
yAxis <- rnorm(200) + xAxis / 10
lowBand <- yAxis + rnorm(200, - 1.5, 0.1)
highBand <- yAxis + rnorm(200, + 1.5, 0.1)
# create data frame from above data vectors
sample_data <- data.frame(xAxis, yAxis, lowBand, highBand)
# load library ggplot2
library("ggplot2")
# create ggplot2 scatter plot
ggplot(sample_data, aes(xAxis, yAxis)) +
geom_point()+
# geom_ribbon function is used to add confidence interval
geom_ribbon(aes(ymin = lowBand, ymax = highBand),
alpha = 0.2, fill="green", color="green")
输出