查看原文
其他

基于 ggdensity 包的等高线绘制

庄闪闪 庄闪闪的R语言手册 2023-05-04

‍点击下方公众号,回复资料分享,收获惊喜

简介

科研过程中,需要绘制某个后验密度/其他的形状。在发表论文中常常使用等高线来满足该需求。例如:文献[1]中所给出的图:

今天小编主要学习下 ggdensity[2] 来绘制不同类型的等高线,以便今后查阅和使用。并在此基础上,简单学习了另一种方式(ggblanket[3] 包)构建等高线。全文使用 [ggsci]((https://nanx.me/ggsci/ "ggsci")) 来修改配色。

主要参考的资料有1[4]2[5]

教程

数据介绍

本文使用常用数据集 iris 来作为例子。该数据集的前 6 行数据如下所示:

使用的 R 包包括:

library(ggdensity)
library(ggblanket)
library(ggsci)

版本一

使用 geom_hdr() 绘制等高线,配合 facet_wrap() 分面和 ggsci 包中的 scale_fill_aaas()修改配色方案。这是最简单的版本,其实大体上已经符合我的需求了。接下来展示在此基础上的一些调整,供大家以后参考使用。

ggplot(iris,aes(x = Sepal.Width, y = Sepal.Length, fill = Species)) +
  geom_hdr() + 
  scale_fill_aaas() +
  facet_wrap(vars(Species)) 

版本二

为了说明各个点的位置,可以直接在原来基础上增加代码:geom_point(shape = 21)

# 增加点
ggplot(iris,aes(x = Sepal.Width, y = Sepal.Length, fill = Species)) +
  geom_hdr() + 
  geom_point(shape = 21) +
  scale_fill_aaas() +
  facet_wrap(vars(Species)) 

版本三

使用 geom_hdr_lines() 配合 geom_point(),得到等高线(没有填充)和对应点。当然如果你觉得点的颜色太花了,可以在geom_point() 设置 color = "black"

ggplot(iris,aes(x = Sepal.Width, y = Sepal.Length, color = Species)) +
  geom_hdr_lines() +
  geom_point() +
  scale_color_aaas() +
  facet_wrap(vars(Species)) 
 

版本四

在原来的基础上,使用 geom_hdr_rug() 加入地毯。


ggplot(iris,aes(x = Sepal.Width, y = Sepal.Length, fill = Species)) +
  ggdensity::geom_hdr() + 
  geom_point(shape = 21) +
  scale_fill_aaas() +
  facet_wrap(vars(Species)) +
  geom_hdr_rug()

版本五

这里还可以使用 {ggblanket} 包绘制,该包集成了 ggplot 的语法,对新手使用更加方便。例如,iris 包绘制等高线可由以下代码实现。

iris |>
  gg_blank(
    x = Sepal.Width,
    y = Sepal.Length,
    col = Species,
    facet = Species,
    col_legend_place = "r") +
  ggdensity::geom_hdr(colour = NA) +
  labs(alpha = "Probs") +
  theme(legend.title = element_text(margin = margin(t = 5)))

小编有话说


  • 关于文章所提的文献中的图,本文并没有做复现工作,使用 geom_hdr_lines()factet_wrap(), geom_text()annotate() 基本就可以满足需求。



注意:本文的代码(.RMD)已经放到我的 GitHub 中(文末原文直达),有兴趣读者可以下载。此外,往期部分推文代码都已经公开,欢迎大家 Fork,star 使用。

参考资料

[1]

文献: Fang, G. (2020). Multivariate Statistical Modeling and Analysis of Accelerated Degradation Testing Data for Reliability Prediction.

[2]

ggdensity: https://cloud.r-project.org/web/packages/ggdensity/index.html

[3]

ggblanket: https://davidhodge931.github.io/ggblanket/articles/ggblanket.html

[4]

1: https://jamesotto852.github.io/ggdensity/

[5]

2: https://davidhodge931.github.io/ggblanket/articles/ggblanket.html

推荐: 可以保存以下照片,在b站扫该二维码,或者b站搜索【庄闪闪】观看Rmarkdown系列的视频教程。Rmarkdown视频新增两节视频(写轮眼幻灯片制作)需要视频内的文档,可在公众号回复【rmarkdown】


R沟通|Rmarkdown教程(4)


R沟通|Rmarkdown教程(3)


R沟通|Rmarkdown教程(2)


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存