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

如何在Quarto HTML报告中控制图片尺寸?设置无效问题求助

问题:Quarto中使用fig.height/fig-height设置图片尺寸无效

我尝试用代码块选项fig.height和fig-height调整图片尺寸,但图片大小完全没变化。以下是我的Quarto文档代码及效果截图:

---
title: '图片尺寸测试'
author: 'Joseph Powers'
date: 2024-05-07
format:
    html:
        toc: true
        toc-depth: 3
        html-math-method: webtex
editor: source
fig.align: 'center'
dpi: 300
include: TRUE
echo: FALSE
message: FALSE
warning: FALSE
error: FALSE
cache: FALSE
code-fold: true
df-print: kable
---

```{python}
import pandas as pd
import numpy as np
from plotnine import *
from mizani.formatters import percent_format
from scipy import stats

my_blue = '#0177c9'
my_red = '#bd0707'

x = np.random.normal(.05, .025, 4000)

# 用KDE估计概率密度函数
pdf = stats.gaussian_kde(x)

# 在一系列点上计算PDF值
points = np.linspace(min(x), max(x), 1000)
estimated_density = pdf.evaluate(points)

df_dens = pd.DataFrame({
    'x': points,
    'y': estimated_density
})

p = (ggplot(df_dens, aes('x', 'y')) +
 geom_line() +
 geom_area(data = df_dens[df_dens['x'] >= 0], fill = my_blue) +
 geom_area(data = df_dens[df_dens['x'] <= 0], fill = my_red) +
 theme_bw() +
 theme(panel_grid=element_blank(), axis_text_y=element_blank(), axis_ticks_y=element_blank()) +
 labs(y='', x="\n潜在处理效应") +
 scale_x_continuous(
    breaks=np.arange(-1, 1.01, 0.01),
    labels=percent_format()
    ) 
)

p
#| out-width: '20%'
#| out-height: '20%'
p
#| fig-height: 3
#| fig-width: 10
p
#| fig-height: 1
#| fig-width: 1
p
![图片尺寸设置无效的效果截图](https://i.sstatic.net/IYtQxaeW.png)

---

## 解决方法

问题根源是你直接输出了之前代码块中已经生成好的plotnine图形对象`p`,而Quarto的`fig-height`/`fig-width`参数只对**当前代码块内实时生成的图形**生效,无法修改已生成图形对象的尺寸。

你可以通过两种方式解决:

1. **在图形生成的代码块中指定尺寸**
   如果只需要一次特定尺寸的图形,直接把参数加到创建并输出`p`的代码块上:
   ```python
   #| fig-height: 3
   #| fig-width: 10
   # ... 导入库、数据处理代码不变 ...
   p = (ggplot(...) + ...)
   p
  1. 复用图形对象时强制重新渲染
    若要复用已创建的p,在输出时调用p.draw()确保图形在当前代码块内重新渲染,同时配合尺寸参数:
    #| fig-height: 1
    #| fig-width: 1
    p.draw()
    

另外补充:out-width/out-height是控制图形在页面中的显示比例(如占容器的百分比),不修改图形本身的分辨率尺寸;如果只是调整页面显示大小,这个参数是有效的,但要修改图形的实际生成尺寸,必须配合实时生成的图形使用fig-height/fig-width。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:45:07