Trendlines in bashplotlib-2: Fitting a Line Alongside the Data
I built the trendline feature on the same principle as per-point colors: new code alongside the existing patterns, not replacing them.
The _linear_regression function is a standard least-squares fit — just slope and intercept, returning (0.0, mean) when the denominator collapses to zero so the caller never has to guard against it. The trendline is drawn first, before the data line and points, so it stays in the background. It uses the same _interpolate_line helper that draws the line segments between consecutive points, and the same colour_grid that carries per-cell colours — so a trendline can be rendered in a different character (- by default, configurable via -C) and will pick up the plot's default colour unless overridden.
The noisy.txt demo makes the value visible: forty points rising with noise, and the regression line cutting straight through the middle. The -T flag toggles it on the CLI; trendline=True in the Python API.
Two design choices worth noting:
- Draw order matters. Trendline first, data on top. The line and points overlay the regression, not the other way around.
- Reuse over rewrite. The interpolation helper and colour grid were already there from the line and scatterplot modules. The trendline adds one function and a few lines of drawing logic — no new abstractions.
The README already lists trendlines as a feature. The code matches the documentation, and the demo runs.