R语言 在ggplot2中使用ggforce的Hull Plots实现集群的可视化

R语言 在ggplot2中使用ggforce的Hull Plots实现集群的可视化

HULL图也被称为分组散点图,因为这些图是用来将散点图按聚类分隔开来的。当人们想将数据中存在的聚类可视化时,Hull图就更有用了。R语言中的Hull图可以通过ggforce包中的geom_mark_hull()函数来绘制。

geom_mark_hull()方法的语法

语法: geom_mark_hull(mapping,data,concavity,radius,position)

其中

  • mapping – 由aeS()函数创建的一组审美贴图
  • data – 要显示的数据框
  • concavity – 用来设置船体的凹度
  • radius – 用来指定角的半径
  • position – 用来调整位置。

使用船体图可视化集群的步骤

第1步: 首先,我们需要安装所需的软件包(ggplot2,ggforce)并加载它们。

# Install Required Packages
install.packages("ggplot2")
install.packages("ggforce")
 
# Load the installed Packages
library(ggplot2)
library(ggforce)
R

第2步: 接下来我们需要使用ggplo2软件包中的ggplot()函数绘制基本的散点图。

# Load the default dataset (iris)
data(iris)
 
# Plotting the scatter plot using ggplot2 package
fig1<-ggplot2::ggplot(aes
                      (Sepal.Length,Sepal.Width),
                      data=iris)+geom_point()
print(fig1)
R

输出

在ggplot2中使用ggforce的Hull Plots实现集群的可视化

第3步: 稍后我们将使用ggforce软件包中的geom_mark_hull()函数为该散点图添加hulls(集群)。

# Load the default dataset (iris)
data(iris)
 
# Plotting the scatter plot using ggplot2 package
fig1<-ggplot2::ggplot(aes(Sepal.Length,Sepal.Width),data=iris)+geom_point()
 
# Plotting the Hull Plot using ggforce package
fig2 <- fig1 + ggforce::geom_mark_hull
    (aes(fill=Species,label=Species),
             concavity=2)
 
print(fig2)
R

输出

在ggplot2中使用ggforce的Hull Plots实现集群的可视化

第4步: 我们还可以使用ggforce包的labs()函数在R中定制Hull图,为其添加标签,并使用expand_limits()可以扩展绘制图形时需要考虑的x轴和y轴数值的限制。

# Load the default dataset (iris)
data(iris)
 
# Plotting the scatter plot using ggplot2 package
fig1<-ggplot2::ggplot(aes
   (Sepal.Length,Sepal.Width),data=iris)+geom_point()
 
# Plotting the Hull Plot using ggforce package
fig2 <- fig1 + ggforce::geom_mark_hull(aes
          (fill=Species,label=Species),concavity=2)
 
# Customized Hull Plot
fig3 <- fig2 + ggforce::geom_mark_hull
    (aes(fill=Species,label=Species),concavity=2)+
       expand_limits(x=8.5,y=5.0)+
       labs(title="Customized Hull Plot using R",
            subtitle = "Iris Dataset",
            x="Sepal Length",y="Sepal Width")
 
print(fig3)
R

输出

在ggplot2中使用ggforce的Hull Plots实现集群的可视化

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册