R 中的直方图和密度图
直方图是一种图形表示,它将一组数据点组织到用户指定的范围内,并近似表示数值数据的分布。
在 R 语言中,直方图是使用 hist()函数构建的。
Syntax: hist(v,main,xlab,xlim,ylim,breaks,col,border)
Parameters:
- v:- It is a vector containing numeric values used in the histogram.
- main:-It indicates the title of the chart.
- col:- It is used to set the color of the bars.
- border:-It is used to set the border color of each bar.
- xlab:-It is used to give a description of the x-axis.
- xlim:-It is used to specify the range of values on the x-axis.
- ylim:-It is used to specify the range of values on the y-axis.
- breaks:-It is used to mention the width of each bar.
Return: It will return the histogram.
例子:-
R
v <- c(5,9,13,2,50,20,59,36,23,2,8,27,72,14)
hist(v,xlab = "Weight",col = "red",border = "black")
R
library(readxl)
library(ggplot2)
Salary_Data <- read_excel("Salary_Data.xls")
den <- density(Salary_Data$YearsExperience)
plot(den, frame = FALSE, col = "blue",main = "Density plot")
R
hist(beaver1$temp,
col="green",
border="black",
prob = TRUE,
xlab = "temp",
main = "GFG")
lines(density(beaver1$temp),
lwd = 2,
col = "chocolate3")
输出:
密度图是数值变量分布的表示,它使用核密度估计来显示变量的概率密度函数。在 R 语言中,我们使用 density()函数来帮助计算核密度估计。并进一步使用其返回值来构建最终的密度图。
Syntax: density(x)
Parameters:
- x: the data from which the estimate is to be computed
Returns:
It will return the kernel density.
例子:
使用的数据集链接:-Link
电阻
library(readxl)
library(ggplot2)
Salary_Data <- read_excel("Salary_Data.xls")
den <- density(Salary_Data$YearsExperience)
plot(den, frame = FALSE, col = "blue",main = "Density plot")
输出:
我们还可以在同一帧中创建直方图和密度图。
例子:
电阻
hist(beaver1$temp,
col="green",
border="black",
prob = TRUE,
xlab = "temp",
main = "GFG")
lines(density(beaver1$temp),
lwd = 2,
col = "chocolate3")
输出: