在上一篇教程中,我们生成了一个可交互的图象。在本篇教程中将会介绍如何将此类可交互图象上传至自己的Hexo博客。

以.html格式导出交互式图象

在R中运行以下代码,图象会以’.html’格式默认保存在R项目文件夹中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 安装必要包
if (!require("plotly")) install.packages("plotly")
if (!require("htmlwidgets")) install.packages("htmlwidgets")

library(plotly)
library(htmlwidgets)

# 一次性获取所有需要的数据
meta_data <- FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA"))

# 转换为plotly对象时直接绑定数据
interactive_plot <- plotly::ggplotly(
plot +
aes(text = paste(
"Ident:", meta_data$ident, "\n",
"PC1:", round(meta_data$PC_1, 2), "\n",
"Genes:", meta_data$nFeature_RNA
)),
tooltip = "text"
)

# 保存交互式图表
htmlwidgets::saveWidget(
widget = interactive_plot,
file = "MS4A1_Interactive.html",
title = "MS4A1 Expression Interactive Plot"
)

在hexo/source文件夹中新建html文件夹

就像新建images文件夹来存储博客中的图片一样,我们可以新建html文件夹用来存储上述.html格式的交互式图象。

新建好文件夹之后,记得将R项目文件夹中的MS4A1_Interactive.html拷贝至html文件夹内。

修改根目录.config.yml配置文件

用记事本打开hexo根目录下的config.yml文件,将下面这段:

1
2
3
4
5
6
7
8
9
# Directory
source_dir: source
public_dir: public
tag_dir: tags
archive_dir: archives
category_dir: categories
code_dir: downloads/code
i18n_dir: :lang
skip_render:

修改为:

1
2
3
4
5
6
7
8
9
10
# Directory
source_dir: source
public_dir: public
tag_dir: tags
archive_dir: archives
category_dir: categories
code_dir: downloads/code
i18n_dir: :lang
skip_render:
- "html/**" # 跳过渲染指定目录

这是因为Hexo默认会使用Nunjucks模板引擎处理所有HTML文件。而Plotly生成的HTML文件中包含类似{{……}}的JavaScript模板语法,这会被Nunjucks误认为是模板变量,导致解析失败。(看不懂没关系,改掉就可以)

在博客文章.md文件中插入交互式图象

在文章中需要的地方插入下列html代码:

1
2
3
4
5
6
7
<iframe 
src="/html/MS4A1_Interactive.html"
width="100%"
height="600"
frameborder="0"
scrolling="no">
</iframe>

在这之后,hexo三连(hexo clean、hexo g、hexo d)就可以啦!