Skip to content

Commit e8b7ddc

Browse files
committed
Add support for plotting arraymancer tensors
This removes the need to manually wrap arraymancer tensors within a dataframe before plotting them. Two versions of ggplotnim are added: - One that plots a single rank-1 tensor vs its element indexes. - One that plots a rank-1 tensor vs another. Both use the input tensor expressions as labels.
1 parent 272c3ef commit e8b7ddc

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/ggplotnim.nim

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,33 @@ proc ggplot*(data: DataFrame, aes: Aesthetics = aes();
281281
result.theme = Theme(discreteScaleMargin: some(quant(0.2,
282282
ukCentimeter)))
283283

284+
template ggplot*[T](y: Tensor[T]): GgPlot =
285+
## Plot a single rank-1 tensor (vs its element indexes)
286+
##
287+
## Uses the input expression as the "y" label
288+
let y_name = getSymbolName(y)
289+
doAssert y.rank == 1, "ggplot input tensor rank must be 1 but is " & $y.rank
290+
let y_data = y
291+
let x = arange(y_data.len)
292+
let df = toDf({"x": x, y_name: y_data})
293+
ggplot(df, aes("x", y_name)) + geom_line()
294+
295+
template ggplot*[T](x, y: Tensor[T]): GgPlot =
296+
## Plot a rank-1 tensor vs another
297+
##
298+
## Uses the input expressions as the "x" and "y" labels
299+
let x_name = getSymbolName(x)
300+
let y_name = getSymbolName(y)
301+
doAssert x.rank == 1,
302+
"First ggplot input tensor rank must be 1 but is " & $x.rank
303+
doAssert y.rank == 1,
304+
"First ggplot input tensor rank must be 1 but is " & $y.rank
305+
doAssert x.len == y.len,
306+
"ggplot input tensor lengths are not the same (" &
307+
$x.len & " != " & $y.len & ")"
308+
let df = toDf({x_name: x, y_name: y})
309+
ggplot(df, aes(x_name, y_name))
310+
284311
template assignBinFields(res: var Geom, stKind, bins,
285312
binWidth, breaks, bbVal, density: untyped): untyped =
286313
case stKind

0 commit comments

Comments
 (0)