Quarto 入门教程 (3):代码框、图形、数据框设置

简介

本文是《手把手教你使用 Quarto 构建文档》第三期,前两期分别介绍了:

  1. 第一期 介绍了Quarto 构建文档的原理;可创建的文档类型;对应的参考资源分享。

  2. 第二期 介绍了如何使用 Quarto,并编译出文档(PDF,MS Word,html)等。

本期将介绍 Quarto 细节设置部分,目录如下:

代码框展示

根据第二期的内容,读者可以编译出各种格式的文档,默认情况下 HTML 输出结果如下:

隐藏代码

如果读者需要隐藏所有代码,而只展示代码结果,可以通过 echo: false 实现。

---
title: "Quarto Computations"
execute:
  echo: false
---

运行后的结果如下:

如果需要指定展示某个代码,可以在该代码块中加入 echo: true

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

注意:这里的选项设置和 R markdown 非常相似,具体见Rmarkdown教程(3)。例如:evalincludepromptcommentresults 和错误信息选项
warningerrormessage 等。有关其他 Knitr 单元选项详细信息可见

折叠代码

如果读者想折叠代码而不是隐藏所有代码,可使用 code-fold

---
title: "Quarto Computations"
format:
  html:
    code-fold: true
---

code-fold:代码折叠

还可以提供对代码折叠的全局控制,尝试添加 code-tools:

---
title: "Quarto Computations"
format:
  html:
    code-fold: true
    code-tools: true
---

图形设置

可以通过设置 fig-widthfig-height 来改变宽高比;fig-cap 修改标签以进行交叉引用;fig-alt 添加替代文本。

交叉引用

使用以下代码设置图片展示效,并使用 @fig-scatterplot 进行交叉引用。

#| label: fig-scatterplot
#| fig-cap: "City and highway mileage for 38 popular models of cars."
#| fig-alt: "Scatterplot of city vs. highway mileage for cars, where points are colored by the number of cylinders. The plot displays a positive, linear, and strong relationship between city and highway mileage, and mileage increases as the number of cylinders decreases."
#| fig-width: 6
#| fig-height: 3.5

多图排版

如果读者想并排两个图形,并为每个图添加描述性小标题。可以配合
使用 layout-ncol: 2fig-capfig-subcap。读者可以使用 @fig-mpg 引用母图。 @fig-mpg-1@fig-mpg-2 引用子图。

#| label: fig-mpg
#| fig-cap: "City and highway mileage for 38 popular models of cars."
#| fig-subcap:
#|   - "Color by number of cylinders"
#|   - "Color by engine displacement, in liters"
#| layout-ncol: 2
#| column: page

ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
  geom_point(alpha = 0.5, size = 2) +
  scale_color_viridis_c() +
  theme_minimal()

ggplot(mpg, aes(x = hwy, y = cty, color = displ)) +
  geom_point(alpha = 0.5, size = 2) +
  scale_color_viridis_c(option = "E") +
  theme_minimal()

数据框

可以使用 df-print 文档选项控制默认情况下打印数据框的方式。 可用选项包括:

选项描述
default将默认的S3方法用于数据框架。
kable使用 knitr::kable()函数生成 Markdown 表格。
tibble使用 tibble 包的纯文本表。
paged使用 rmarkdown::paged_table() 实现带有行和列溢出分页的 HTML 表格。

例如,指定对数据框进行分页打印:

---
title: "Document"
format: 
   html:
     df-print: paged
---

内联代码

要在 markdown 中包含可执行表达式,请将表达式括在'r'中。 例如,我们可以使用内联代码来说明数据中的观察数量:

我们数据中包含了 `r nrow(mpg)` 个数据。

缓存

如果文档包含计算时间过长的代码块,读者可能需要缓存这些代码块的结果。可以在 YAML 执行选项中设置 cache: true

execute:
  cache: true

缓存所有代码块可能不合适,也可以在特定的代码块中设置:

#| cache: true

渲染文档时,将看到在工作目录中创建了一个新文件夹,其名称与文档相同,后缀为 _cache。该文件夹包含缓存的结果。如果读者对该方面感兴趣,可见详细缓存细节

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值