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

如何在Typst中设置图表自动宽度?适配95%页面宽度

在Typst中设置图表为页面宽度95%的方法

在Typst里,对应LaTeX的\textwidth(页面文本区域宽度)和\linewidth(当前上下文行宽),有两个内置函数可以直接调用:

  • textwidth():获取页面文本区域的总宽度,和LaTeX的\textwidth作用一致
  • linewidth():获取当前上下文的行宽(比如在列表、分栏等环境中会比页面文本宽度窄),对应LaTeX的\linewidth

要把图表设置为当前页面宽度的95%,你有两种简洁的实现方式:

方式一:直接使用百分比值

直接给图表的width参数设置95%,Typst默认会基于当前上下文的行宽(即linewidth())来计算:

#let xs = range(9)
#let ys = (12, 51, 23, 36, 38, 15, 10, 22, 86)

#lq.diagram(
  width: 95%, // 直接设置为当前行宽的95%
  xaxis: (subticks: none),

  lq.bar(
    xs, ys
  ),

  ..xs.zip(ys).map(((x, y)) => {
    let align = if y > 12 { top } else { bottom }
    lq.place(x, y, pad(0.2em)[#y], align: align)
  })
)

方式二:结合内置函数精确控制

如果需要明确基于页面文本宽度(而非当前上下文行宽)来计算,可以用textwidth() * 0.95:

#let xs = range(9)
#let ys = (12, 51, 23, 36, 38, 15, 10, 22, 86)

#lq.diagram(
  width: textwidth() * 0.95, // 基于页面文本宽度的95%
  xaxis: (subticks: none),

  lq.bar(
    xs, ys
  ),

  ..xs.zip(ys).map(((x, y)) => {
    let align = if y > 12 { top } else { bottom }
    lq.place(x, y, pad(0.2em)[#y], align: align)
  })
)

如果你的图表处于特殊上下文(比如分栏、列表中),想要匹配当前环境的行宽的95%,就用linewidth() * 0.95替换width参数的值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 18:04:58