如何用Python优化Quarto中Markdown条件代码块的效率?
Quarto中Plotly绘图多输出格式自动适配方案
自定义函数实现一键适配
Quarto自带quarto::quarto_format_is()函数,能准确检测当前输出格式,比knitr的is_html_output()更适配Quarto环境。我们可以封装一个函数,自动根据输出格式选择交互式Plotly图(HTML)或静态图片(docx/pdf)。
1. 定义适配函数
在文档开头的代码块中添加以下代码:
library(plotly) library(webshot2) # 用于导出Plotly为静态图片 display_plot <- function(plotly_fig) { # 检测输出格式 if (quarto::quarto_format_is("html")) { # HTML输出:直接返回交互式Plotly图 plotly_fig } else { # docx/pdf输出:导出为静态PNG并插入文档 temp_png <- tempfile(fileext = ".png") plotly::export(plotly_fig, file = temp_png) knitr::include_graphics(temp_png) } }
2. 单次绘图,自动适配
之后只需写一次绘图逻辑,调用display_plot()即可:
# 示例:创建Plotly图表 car_plot <- plot_ly(mtcars, x = ~wt, y = ~mpg, type = "scatter", mode = "markers") # 自动适配输出格式 display_plot(car_plot)
无函数替代方案:单代码块条件执行
如果不想封装函数,也可以在单个代码块内用Quarto的eval参数实现条件执行,避免重复代码:
#| eval: quarto::quarto_format_is("html") # HTML输出展示交互式图 car_plot <- plot_ly(mtcars, x = ~wt, y = ~mpg, type = "scatter", mode = "markers") car_plot #| eval: !quarto::quarto_format_is("html") # docx/pdf输出导出静态图 car_plot <- plot_ly(mtcars, x = ~wt, y = ~mpg, type = "scatter", mode = "markers") temp_png <- tempfile(fileext = ".png") plotly::export(car_plot, file = temp_png) knitr::include_graphics(temp_png)
关键注意事项
- 安装依赖包:执行
install.packages(c("quarto", "webshot2"))确保功能正常 webshot2首次使用可能需要安装Chrome/Chromium驱动,按控制台提示操作即可- 若使用ggplot转Plotly(
ggplotly()),上述方案完全兼容
内容的提问来源于stack exchange,提问作者WillieMcTell
相关产品推荐
相关产品推荐

