R绘制山峦图主要采用ggridges包绘制,下面我们结合iris示例给大家演示山峦图的绘制。


# 老规矩,先加载包
library(ggplot2)
library(ggridges)
library(tidyverse)
library(gridExtra)
library(ggpubr)

# 根据Sepal.Length绘制山峦图
p1 <- ggplot(iris) +
    # geom_ridgeline():主要绘制山脊线图
    # geom_density_ridges():主要根据密度绘制山脊线图
    geom_density_ridges_gradient(aes(x = `Sepal.Length`, y = `Species`, fill = ..x..), scale = 3,
                                 rel_min_height = 0.01,
                                 gradient_lwd = 0.1) +
    scale_x_continuous(expand = c(0.01, 0)) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_fill_viridis(name = "Value", option = "C") +
    # 标题设置
    labs(title = "Sepal.Length") +
    # 主题设置
    theme_ridges(font_size = 13, grid = T) +
    theme(axis.title.y = element_blank())
p2 <- ggplot(iris) +
    geom_density_ridges_gradient(aes(x = `Sepal.Width`, y = `Species`, fill = ..x..), scale = 3,
                                 rel_min_height = 0.01,
                                 show.legend = T,
                                 gradient_lwd = 0.1) +
    scale_x_continuous(expand = c(0.01, 0)) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_fill_viridis(name = "Value", option = "C") +
    labs(title = "Sepal.Width") +
    theme_ridges(font_size = 13, grid = FALSE) +
    theme(axis.title.y = element_blank())
p3 <- ggplot(iris) +
    geom_density_ridges_gradient(aes(x = `Petal.Length`, y = `Species`, fill = ..x..), scale = 3,
                                 rel_min_height = 0.01,
                                 gradient_lwd = 0.1) +
    scale_x_continuous(expand = c(0.01, 0)) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_fill_viridis(name = "Value", option = "C") +
    labs(title = "Petal.Length") +
    theme_ridges(font_size = 13, grid = FALSE) +
    theme(axis.title.y = element_blank())
p4 <- ggplot(iris) +
    geom_density_ridges_gradient(aes(x = `Petal.Width`, y = `Species`, fill = ..x..), scale = 3,
                                 rel_min_height = 0.01,
                                 gradient_lwd = 0.1) +
    scale_x_continuous(expand = c(0.01, 0)) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_fill_viridis(name = "Value", option = "C") +
    labs(title = "Petal.Width") +
    theme_ridges(font_size = 13, grid = FALSE) +
    theme(axis.title.y = element_blank())
# 组合各个图片
ggarrange(
    p1,
    p2,
    p3,
    p4,
    ncol = 2,
    nrow = 2,
    common.legend = TRUE, # legend共用
    legend = "right" # 右侧显示legend
)

如此一个漂亮的山峦图绘制好了。

参考文章:

1.https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html