Skip to content

Commit

Permalink
Merge pull request #59 from guptarohit/fix-small-data-height
Browse files Browse the repository at this point in the history
Fix graph height calculation for small value ranges
  • Loading branch information
guptarohit authored Oct 26, 2024
2 parents 13d971f + 7de513c commit 1919005
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 11 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to this project will be documented in this file.

## [0.7.3] - 2024-10-26

### Fixed

- Incorrect plot height calculation for small value ranges (#59)

## [0.7.2] - 2024-08-12

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM golang:1.17-alpine AS builder
FROM golang:1.23-alpine AS builder
WORKDIR /app
COPY cmd ./cmd
COPY go.mod ./
Expand Down
16 changes: 6 additions & 10 deletions asciigraph.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ func PlotMany(data [][]float64, options ...Option) string {

minimum, maximum := math.Inf(1), math.Inf(-1)
for i := range data {
min, max := minMaxFloat64Slice(data[i])
if min < minimum {
minimum = min
minVal, maxVal := minMaxFloat64Slice(data[i])
if minVal < minimum {
minimum = minVal
}
if max > maximum {
maximum = max
if maxVal > maximum {
maximum = maxVal
}
}
if config.LowerBound != nil && *config.LowerBound < minimum {
Expand All @@ -65,11 +65,7 @@ func PlotMany(data [][]float64, options ...Option) string {
interval := math.Abs(maximum - minimum)

if config.Height <= 0 {
if int(interval) <= 0 {
config.Height = int(interval * math.Pow10(int(math.Ceil(-math.Log10(interval)))))
} else {
config.Height = int(interval)
}
config.Height = calculateHeight(interval)
}

if config.Offset <= 0 {
Expand Down
13 changes: 13 additions & 0 deletions asciigraph_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,19 @@ func TestPlot(t *testing.T) {
`
\x1b[94m 1.00\x1b[0m \x1b[32m┤\x1b[0m╶
\x1b[91mcolor test\x1b[0m`},
{
[]float64{.02, .03, .02},
nil,
`
0.030 ┤╭╮
0.020 ┼╯╰`},
{
[]float64{.2, .3, .1, .3},
nil,
`
0.30 ┤╭╮╭
0.20 ┼╯││
0.10 ┤ ╰╯`},
}

for i := range cases {
Expand Down
14 changes: 14 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,17 @@ func init() {
}
}
}

func calculateHeight(interval float64) int {
if interval >= 1 {
return int(interval)
}

scaleFactor := math.Pow(10, math.Floor(math.Log10(interval)))
scaledDelta := interval / scaleFactor

if scaledDelta < 2 {
return int(math.Ceil(scaledDelta))
}
return int(math.Floor(scaledDelta))
}

0 comments on commit 1919005

Please sign in to comment.