Skip to content

Commit

Permalink
Add LowerBound and UpperBound options
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosms authored and guptarohit committed Jun 21, 2023
1 parent 2f4643b commit 3590b35
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 8 deletions.
6 changes: 6 additions & 0 deletions asciigraph.go
Expand Up @@ -48,6 +48,12 @@ func PlotMany(data [][]float64, options ...Option) string {
maximum = max
}
}
if config.LowerBound != nil && *config.LowerBound < minimum {
minimum = *config.LowerBound
}
if config.UpperBound != nil && *config.UpperBound > maximum {
maximum = *config.UpperBound
}
interval := math.Abs(maximum - minimum)

if config.Height <= 0 {
Expand Down
38 changes: 38 additions & 0 deletions asciigraph_test.go
Expand Up @@ -201,6 +201,44 @@ func TestPlot(t *testing.T) {
38.46 ┤ ││ │││
37.46 ┤ ╰╯ │││
36.45 ┤ ╰╯╰`},
{
[]float64{2, 1, 1, 2, -2, 5, 7, 11, 3, 7, 4, 5, 6, 9, 4, 0, 6, 1, 5, 3, 6, 2},
[]Option{LowerBound(-3), UpperBound(13)},
` 13.00 ┤
12.00 ┤
11.00 ┤ ╭╮
10.00 ┤ ││
9.00 ┤ ││ ╭╮
8.00 ┤ ││ ││
7.00 ┤ ╭╯│╭╮ ││
6.00 ┤ │ │││ ╭╯│ ╭╮ ╭╮
5.00 ┤ ╭╯ │││╭╯ │ ││╭╮││
4.00 ┤ │ ││╰╯ ╰╮││││││
3.00 ┤ │ ╰╯ ││││╰╯│
2.00 ┼╮ ╭╮│ ││││ ╰
1.00 ┤╰─╯││ ││╰╯
0.00 ┤ ││ ╰╯
-1.00 ┤ ││
-2.00 ┤ ╰╯
-3.00 ┤`},
{
[]float64{2, 1, 1, 2, -2, 5, 7, 11, 3, 7, 4, 5, 6, 9, 4, 0, 6, 1, 5, 3, 6, 2},
[]Option{LowerBound(0), UpperBound(3)},
` 11.00 ┤ ╭╮
10.00 ┤ ││
9.00 ┤ ││ ╭╮
8.00 ┤ ││ ││
7.00 ┤ ╭╯│╭╮ ││
6.00 ┤ │ │││ ╭╯│ ╭╮ ╭╮
5.00 ┤ ╭╯ │││╭╯ │ ││╭╮││
4.00 ┤ │ ││╰╯ ╰╮││││││
3.00 ┤ │ ╰╯ ││││╰╯│
2.00 ┼╮ ╭╮│ ││││ ╰
1.00 ┤╰─╯││ ││╰╯
0.00 ┤ ││ ╰╯
-1.00 ┤ ││
-2.00 ┤ ╰╯`},

{
[]float64{1, 1, math.NaN(), 1, 1},
nil,
Expand Down
29 changes: 21 additions & 8 deletions options.go
Expand Up @@ -11,14 +11,15 @@ type Option interface {

// config holds various graph options
type config struct {
Width, Height int
Offset int
Caption string
Precision uint
CaptionColor AnsiColor
AxisColor AnsiColor
LabelColor AnsiColor
SeriesColors []AnsiColor
Width, Height int
LowerBound, UpperBound *float64
Offset int
Caption string
Precision uint
CaptionColor AnsiColor
AxisColor AnsiColor
LabelColor AnsiColor
SeriesColors []AnsiColor
}

// An optionFunc applies an option.
Expand Down Expand Up @@ -59,6 +60,18 @@ func Height(h int) Option {
})
}

// LowerBound sets the graph's minimum value for the vertical axis. It will be ignored
// if the series contains a lower value.
func LowerBound(min float64) Option {
return optionFunc(func(c *config) { c.LowerBound = &min })
}

// UpperBound sets the graph's maximum value for the vertical axis. It will be ignored
// if the series contains a bigger value.
func UpperBound(max float64) Option {
return optionFunc(func(c *config) { c.UpperBound = &max })
}

// Offset sets the graphs offset.
func Offset(o int) Option {
return optionFunc(func(c *config) { c.Offset = o })
Expand Down

0 comments on commit 3590b35

Please sign in to comment.