You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quarto条件语句内并排图无法正常渲染问题咨询

问题原因与解决方法

这不是Quarto的bug,是你对R代码块的执行逻辑存在误解。在R中,代码块里只有最后一行表达式的结果会被自动输出(渲染)。你的else分支里虽然写了两个ggplot语句,但第一个ggplot没有被主动触发输出,只有最后一个会被返回并渲染。

解决方法

方法1:主动用print()输出每个图

修改条件分支内的代码,给每个ggplot调用加上print(),强制输出每个图表:

#| layout-ncol: 2
#| out-width: "50%"

test <- F

if(test){
  print(ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point())
} else {
  print(ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point())
  print(ggplot(mtcars, aes(x = hp, y = disp)) + geom_point())
}

方法2:用列表包裹多个图

把两个ggplot对象放入列表中,R会自动遍历列表并输出所有元素:

#| layout-ncol: 2
#| out-width: "50%"

test <- F

if(test){
  ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()
} else {
  list(
    ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point(),
    ggplot(mtcars, aes(x = hp, y = disp)) + geom_point()
  )
}

方法3:用patchwork包组合成单个图对象

如果需要更灵活的排版控制,可以使用patchwork包将多个图表组合成一个单独的对象,这样即使在条件分支中也能正常渲染并排布局:

#| layout-ncol: 2
#| out-width: "50%"
library(patchwork)

test <- F

if(test){
  ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()
} else {
  (ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()) +
  (ggplot(mtcars, aes(x = hp, y = disp)) + geom_point())
}

内容的提问来源于stack exchange,提问作者MikeS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:50:07