如何在 R 中创建频率多边形?
在本文中,我们将讨论如何在 R 编程语言中创建频率多边形。
频率多边形是数据框中的值的图,用于可视化值分布的形状。它帮助我们比较不同的数据帧并可视化数据帧的累积频率分布。频率多边形表示数据框中每个不同类的出现次数。
在基础 R 中创建频率多边形:
为了在 R 语言中创建一个基本频率多边形,我们首先为正在构建的变量创建一个线图。然后我们使用polygon()函数来创建频率多边形。
Syntax: plot( x, y ) polygon( c( xmin, x, xmax ), c( ymin, y, ymax ), col )
where,
- x and y: determines the data vector for x and y axes data.
- xmin and ymin: determines the minimum limit of x and y axis.
- xmax and ymax: determines the maximum limit of x and y axis.
- col: determines the color of frequency polygon.
例子:
这里,是使用 Polygon()函数在 Base R 中制作的基本频率多边形。
R
set.seed(999)
x<-1:40
y<-sample(5:40,40,replace=TRUE)
plot(x,y,type="l")
polygon(c(1,x,40),c(0,y,0),col="green")
R
library(ggplot2)
# make this example reproducible
set.seed(0)
# create data frame
index<-1:40
y<-sample(5:40,40,replace=TRUE)
df <- data.frame( index, y )
# create frequency polygon using geom_freqpoly()
# function
ggplot(df, aes(y)) +
geom_freqpoly(bins=10)
R
library(ggplot2)
# make this example reproducible
set.seed(0)
# create data frame
index<-1:40
y<-sample(5:40,40,replace=TRUE)
df <- data.frame( index, y )
# create frequency polygon filled with custom color
ggplot(df, aes(y)) +
geom_area(aes(y=..count..), bins=10, stat='bin', fill='green')
输出:
使用 ggplot2 创建频率多边形:
要使用 ggplot2 包在 R 语言中创建基本频率多边形,我们使用 geom_freqpoly()函数。默认情况下,ggplot2 使用 30 个 bin 来创建频率多边形。通过减少 bin 的数量,您可以使绘图上的线条更平滑。
Syntax: ggplot( df, aes(value)) + geom_freqpoly( bins )
where,
- df: determines the data frame to be visualized.
- value: determines the y-axis column name.
- bins: determines the smoothness of the plot.
例子:
这是使用 ggplot2 包制作的基本频率多边形。
R
library(ggplot2)
# make this example reproducible
set.seed(0)
# create data frame
index<-1:40
y<-sample(5:40,40,replace=TRUE)
df <- data.frame( index, y )
# create frequency polygon using geom_freqpoly()
# function
ggplot(df, aes(y)) +
geom_freqpoly(bins=10)
输出:
使用 ggplot2 包填充颜色的频率多边形:
要使用 ggplot2 包在 R 语言中创建具有填充颜色的基本频率多边形,我们使用 geom_area()函数。我们使用 geom_area()函数的填充参数来用所需的颜色填充频率多边形。
Syntax: ggplot( df, aes(value)) + geom_area(aes(y=..count..), bins, fill )
where,
- df: determines the data frame to be visualized.
- value: determines the y-axis column name.
- bins: determines the smoothness of the plot.
- fill: determines the fill color of the plot:
例子:
这是一个使用 ggplot2 包制作并使用 geom_area()函数着色的基本频率多边形。
R
library(ggplot2)
# make this example reproducible
set.seed(0)
# create data frame
index<-1:40
y<-sample(5:40,40,replace=TRUE)
df <- data.frame( index, y )
# create frequency polygon filled with custom color
ggplot(df, aes(y)) +
geom_area(aes(y=..count..), bins=10, stat='bin', fill='green')
输出: