📜  如何在 R 中绘制多个直方图?

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

如何在 R 中绘制多个直方图?

在本文中,我们将讨论如何在 R 编程语言中绘制多个直方图。

方法 1:Base R 中的多重直方图

要在基础 R 中创建多个直方图,我们首先制作一个直方图,然后在其上添加另一层直方图。但是在这样做时,一些图可能会被剪掉,因为轴是根据第一个图制作的。因此,我们可以在第一个图中添加 xlim 和 ylim 参数,以根据我们的数据集更改轴限制。

句法:

hist( data, col, xlim, ylim )
hist( data, col )

在哪里,

  • data:确定要绘制的数据向量。
  • xlim:确定具有 x 轴限制的向量。
  • ylim:确定有 y 轴限制的向量。
  • col:确定直方图条的颜色。

例子:

这是在基本 R 语言中借助 hist()函数制作的基本多重直方图。

R
# create data vector
x1 = rnorm(1000, mean=60, sd=10)
x2 = rnorm(1000, mean=0, sd=10)
x3 = rnorm(1000, mean=30, sd=10)
  
# create multiple histogram
hist(x1, col='red', xlim=c(-35, 100))
hist(x2, col='green', add=TRUE)
hist(x3, col='blue', add=TRUE)


R
# load library ggplot2
library(ggplot2)
   
# set theme
theme_set(theme_bw(12))
  
# create x vector
xAxis <- rnorm(500)             
  
# create groups in variable using conditional 
# statements
group <- rep(1, 500)              
group[xAxis > -2] <- 2
group[xAxis > -1] <- 3
group[xAxis > 0] <- 4
group[xAxis > 1] <- 5
group[xAxis > 2] <- 6
  
# create sample data frame
sample_data <- data.frame(xAxis, group) 
   
# create histogram using ggplot() 
# function colored by group
ggplot(sample_data, aes(x=xAxis, fill = as.factor(group)))+
   geom_histogram( color='#e9ecef', alpha=0.6, position='identity')


输出:

方法 2:使用 ggplot2 的多个直方图

为了在 ggplot2 中创建多个直方图,我们使用 ggplot2 包的 ggplot()函数和 geom_histogram()函数。为了分别可视化多个组,我们使用美学函数的填充属性通过分类变量为图着色。

句法:

ggplot( df, aes( x, fill ) ) + geom_histogram( color, alpha ) 

在哪里,

  • df:确定要绘制的数据框。
  • x:确定数据变量。
  • 填充:确定直方图中条形的颜色。
  • 颜色:确定直方图中条形边界的颜色。
  • alpha:决定绘图的透明度。

例子:

这里是使用 R 语言中 ggplot2 包的 geom_histogram()函数制作的基本多重直方图。

R

# load library ggplot2
library(ggplot2)
   
# set theme
theme_set(theme_bw(12))
  
# create x vector
xAxis <- rnorm(500)             
  
# create groups in variable using conditional 
# statements
group <- rep(1, 500)              
group[xAxis > -2] <- 2
group[xAxis > -1] <- 3
group[xAxis > 0] <- 4
group[xAxis > 1] <- 5
group[xAxis > 2] <- 6
  
# create sample data frame
sample_data <- data.frame(xAxis, group) 
   
# create histogram using ggplot() 
# function colored by group
ggplot(sample_data, aes(x=xAxis, fill = as.factor(group)))+
   geom_histogram( color='#e9ecef', alpha=0.6, position='identity')

输出: