📜  如何在 R 中创建频率多边形?

📅  最后修改于: 2022-05-13 01:55:29.055000             🧑  作者: Mango

如何在 R 中创建频率多边形?

在本文中,我们将讨论如何在 R 编程语言中创建频率多边形。

频率多边形是数据框中的值的图,用于可视化值分布的形状。它帮助我们比较不同的数据帧并可视化数据帧的累积频率分布。频率多边形表示数据框中每个不同类的出现次数。

在基础 R 中创建频率多边形:

为了在 R 语言中创建一个基本频率多边形,我们首先为正在构建的变量创建一个线图。然后我们使用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 的数量,您可以使绘图上的线条更平滑。

例子:

这是使用 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()函数的填充参数来用所需的颜色填充频率多边形。

例子:

这是一个使用 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')

输出: