R语言 使用R中的Lattice包绘制密度图

R语言 使用R中的Lattice包绘制密度图

密度图主要用于可视化连续数字变量的分布。densityplot()使用内核密度概率估计来计算数字变量的密度概率。在R编程中,密度图可以使用密度图()函数来绘制,该函数存在于lattice包中。

语法: densityplot(x,data, type, xlab, main)

其中。

  • x – 需要将密度可视化的那一(些)列
  • data – 这里指定了数据框架
  • xlab – 用于在绘图中添加X轴标签
  • main – 用来给绘图添加一个标题

在这篇文章中,我们将使用虹膜数据集。首先,我们将绘制简单密度图。在此之前,使用下面的代码安装lattice软件包。

# Install the required package
install.packages("lattice")
# Load the installed package
library(lattice)
  
# Load the default dataset(iris) into current working environment 
data(iris)
  
# Plotting the Simple density plot using densityplot()
lattice::densityplot(~Sepal.Length, data=iris,
                     xlab="Sepal Length",
                     main="Simple Density Plot of iris Dataset")
R

输出

使用R中的Lattice包绘制密度图

我们也可以使用参数 fromto 来指定特定的点 , 输出结果将与上述相同,但只在我们指定的点之间。

# Using from and to
lattice::densityplot(~Sepal.Length, data=iris,
                     xlab="Sepal Length", main="Iris Dataset",
                     from=4, to=6)
R

输出:

使用R中的Lattice包绘制密度图

按照物种类别绘制分区密度图,请遵循下面的代码。

# Plotting the Partitioned density plot using densityplot()
lattice::densityplot(~Sepal.Length|Species, 
                     data=iris, layout=c(1,3),
                     xlab="Sepal Length",
                     main="Partitioned Density Plot of iris Dataset")
R

输出

使用R中的Lattice包绘制密度图

我们也可以通过将类型参数指定为count,绘制基于计数的密度图。

# Plotting the count based density plot using densityplot()
lattice::densityplot(~Sepal.Length|Species, 
                     data=iris, layout=c(1,3), 
                     type="count", xlab=" Sepal Length",
                     main="Count Based Density Plot of iris Dataset")
R

输出

使用R中的Lattice包绘制密度图

让我们看看如何为虹膜数据集绘制定制的密度图。

# Plotting the Customized density plot using densityplot()
lattice::densityplot(~Sepal.Length|Species, data=iris,
                     layout=c(1,3), xlab="Sepal Length",
                     main="Customized Density Plot of iris Dataset",
                     col=c("red","blue","green"))
R

输出

使用R中的Lattice包绘制密度图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册