R语言 如何制作带有边际直方图的散点图
在这篇文章中,我们将讨论如何在R语言中用边际直方图制作散点图。
为此,我们将使用R语言的ggExtra包。ggExtra是一个函数和层的集合,用于增强ggplot2。ggMarginal()函数可以用来为ggplot2的散点图添加边际直方图/博列表/密度图。
安装
要安装ggExtra包,我们使用。
install.packages("ggExtra")
安装完毕后,我们可以加载该软件包,并使用下面的函数来制作带有散点图的边际直方图。
语法: ggMarginal( plot, type=”histogram” )
用边际直方图创建基本散点图
这里,是一个使用 ggExtra 包的 ggMarginal 函数制作的带有边际直方图的基本散点图。
# load library tidyverse and ggExtra
library(tidyverse)
library(ggExtra)
# set theme
theme_set(theme_bw(12))
# create x and y vector
xAxis <- rnorm(1000)
yAxis <- rnorm(1000) + xAxis + 10
# create sample data frame
sample_data <- data.frame(xAxis, yAxis)
# create scatter plot using ggplot() function
plot <- ggplot(sample_data, aes(x=xAxis, y=yAxis))+
geom_point()+
theme(legend.position="none")
# use ggMarginal function to create marginal histogram
ggMarginal(plot, type="histogram")
输出
输出
带有边际直方图的彩色散点图,按组排列
为了给散点图按组着色,我们使用ggplot()函数的col参数。为了给组的边际直方图着色,我们使用groupColour和groupfill为true。
语法: ggMarginal( plot, type=”histogram”, groupColour = TRUE, groupFill = TRUE )
例子: 在这里,我们有一个边际直方图的散点图,都用组来着色。我们根据格式的偏好,对groupColor和groupFill使用布尔值。
# load library tidyverse and ggExtra
library(tidyverse)
library(ggExtra)
# set theme
theme_set(theme_bw(12))
# create x and y vector
xAxis <- rnorm(1000)
yAxis <- rnorm(1000) + xAxis + 10
# create groups in variable using conditional statements
group <- rep(1, 1000)
group[xAxis > -1.5] <- 2
group[xAxis > -0.5] <- 3
group[xAxis > 0.5] <- 4
group[xAxis > 1.5] <- 5
# create sample data frame
sample_data <- data.frame(xAxis, yAxis, group)
# create scatter plot using ggplot()
# function colored by group
plot <- ggplot(sample_data, aes(x=xAxis, y=yAxis,
col = as.factor(group)))+
geom_point()+
theme(legend.position="none")
# use ggMarginal function to create marginal histogram
ggMarginal(plot, type="histogram",
groupColour = TRUE, groupFill = TRUE )
输出
输出