📜  如何使用 R 中的 ggridges 绘制 Ridgeline 图?

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

如何使用 R 中的 ggridges 绘制 Ridgeline 图?

脊线图允许在单个图中将多个类别的数值变量的分布可视化。 ggridges包提供了两种类型的脊线图几何:

  • geom_ridgeline()直接使用高度值来绘制脊线。
  • geom_density_ridges()估计密度,然后制作脊线图。

在本文中,我们将讨论如何使用 R 编程语言的 ggridges 和 ggplot2 库绘制脊线图。

示例 1:创建基本的山脊线图

这是一个基本的山脊线图。为了绘制脊线图,我们首先取一个数据框,在下面的例子中是由 R 语言原生提供的菱形数据框。然后我们使用 geom_density_ridges()函数来绘制脊线图。

R
# load library ggridges and ggplot2
library(ggridges)
library(ggplot2)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot using ggplot and ggridges
ggplot(diamonds, aes(x = price, y = cut)) +
  geom_density_ridges()


R
# load library ggridges and ggplot2
library(ggridges)
library(ggplot2)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot
ggplot(diamonds, aes(x = price, y = cut)) +
  geom_density_ridges()+
scale_x_continuous(trans="log10")# converts scale to log scale


R
# load library ggridges and ggplot2
library(ggridges)
library(ggplot2)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot with color customization
ggplot(diamonds, aes(x = price, y = cut, fill=cut)) +
  geom_density_ridges()


R
# load library ggridges and tidyverse
library(ggridges)
library(tidyverse)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot with color customization
# reorder plot using reorder() function
ggplot(diamonds, aes(x = price, y = fct_reorder(cut,price), fill=cut)) +
  geom_density_ridges()


输出:

示例 3:对数缩放自定义

我们可以使用 scale_x_continuous()函数在 x 轴上绘制对数刻度的脊线图。为了指定转换的类型,我们使用“trans”参数。

电阻

# load library ggridges and ggplot2
library(ggridges)
library(ggplot2)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot
ggplot(diamonds, aes(x = price, y = cut)) +
  geom_density_ridges()+
scale_x_continuous(trans="log10")# converts scale to log scale

输出:



示例 3:颜色自定义

我们可以借助 ggplot()函数的 fill 属性更改绘图的颜色。我们将变量作为参数传递,以根据我们要为绘图着色的内容进行填充。

电阻

# load library ggridges and ggplot2
library(ggridges)
library(ggplot2)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot with color customization
ggplot(diamonds, aes(x = price, y = cut, fill=cut)) +
  geom_density_ridges()

输出:

示例 4:脊线图的重新排序

为了对脊线图重新排序,我们使用 ggplot2 的 reorder()函数。这会根据传递给重新排序函数的参数的均值的递增顺序对绘图进行重新排序。为了以降序重新排列绘图,我们使用 -ve 符号传递变量。

电阻

# load library ggridges and tidyverse
library(ggridges)
library(tidyverse)
  
# Diamonds dataset is provided by R natively
# we will use that same dataset for our plot
# basic ridgeline plot with color customization
# reorder plot using reorder() function
ggplot(diamonds, aes(x = price, y = fct_reorder(cut,price), fill=cut)) +
  geom_density_ridges()

输出: