How do you draw a trend line in typst?

I recently started using lilaq as a replacement for excel. However, I haven’t managed to figure out how you should draw a trend line (linear).

There is no built-in option, and the only method I can think is is finding an external tool that calculates the coordinates for a trend line, and then using that in Typst, but that would be quite inconvenient.

What is the best way to draw a trend line in lilaq, or Typst in general?

Hi @Arnout and welcome!

Check this out: Linear regression · lilaq-project · Discussion #113 · GitHub. Someone provided this code to compute linear regression parameters in the discussions of the Lilaq repository.

You can plot this by lq.plot((x-first, x-last), x => a*x+b)

#let x = (..)
#let y = (..)

#let linear-regression(pairs) = {
  let len = pairs.len()
  let xs = pairs.map(((x, y)) => x)
  let ys = pairs.map(((x, y)) => y)

  let x_ = xs.sum() / len
  let y_ = ys.sum() / len

  let sum_dx2 = xs.map(x => calc.pow(x - x_, 2)).sum()
  let sum_dy2 = ys.map(y => calc.pow(y - y_, 2)).sum()
  let sum_dxdy = pairs.map(((x, y)) => (y - y_) * (x - x_)).sum()

  let a = sum_dxdy / sum_dx2
  let b = y_ - a * x_
  let R = sum_dxdy / (calc.sqrt(sum_dx2) * calc.sqrt(sum_dy2))

  (R: R, a: a, b: b)
}

#let (R, a, b) = linear-regression(x.zip(y))

#lq.diagram(
  lq.plot(x, y),
  lq.plot((x.at(0), x.at(-1)), x => a*x+b, mark: none)
)

Maybe such functionalilty will be included in a future Lilaq version, however the question of the domain is not entirely clear: how long should the line be? This might be very user-specific.

I will take a look, and since it looks like this is the best there is out there right now I will mark this as the solution. Thanks for pointing me in the right direction, and for developing lilaq :hearts:.

1 Like

To clarify, right now I want the trend line to go through the origin, so I suppose I have to do some extra work myself. But, it’s still helpful to have an example on how to approach this.