From 50605907c761ba72f14f9f666775b394202195c8 Mon Sep 17 00:00:00 2001 From: vicanso Date: Thu, 15 Sep 2022 20:09:00 +0800 Subject: [PATCH] feat: support null value for line chart --- charts.go | 13 +++++++++++++ examples/line_chart/main.go | 3 ++- line_chart.go | 5 +++++ painter.go | 9 ++++++++- series.go | 4 ++++ 5 files changed, 32 insertions(+), 2 deletions(-) diff --git a/charts.go b/charts.go index 6d5dc56..f7e52e4 100644 --- a/charts.go +++ b/charts.go @@ -24,6 +24,7 @@ package charts import ( "errors" + "math" "sort" "github.com/wcharczuk/go-chart/v2" @@ -51,6 +52,18 @@ func SetDefaultHeight(height int) { } } +var nullValue = math.MaxFloat64 + +// SetNullValue sets the null value, default is MaxFloat64 +func SetNullValue(v float64) { + nullValue = v +} + +// GetNullValue gets the null value +func GetNullValue() float64 { + return nullValue +} + type Renderer interface { Render() (Box, error) } diff --git a/examples/line_chart/main.go b/examples/line_chart/main.go index 36eabee..97d5859 100644 --- a/examples/line_chart/main.go +++ b/examples/line_chart/main.go @@ -29,7 +29,8 @@ func main() { 120, 132, 101, - 134, + // 134, + charts.GetNullValue(), 90, 230, 210, diff --git a/line_chart.go b/line_chart.go index 0b44cdf..839aa6f 100644 --- a/line_chart.go +++ b/line_chart.go @@ -23,6 +23,8 @@ package charts import ( + "math" + "github.com/golang/freetype/truetype" "github.com/wcharczuk/go-chart/v2/drawing" ) @@ -115,6 +117,9 @@ func (l *lineChart) render(result *defaultRenderResult, seriesList SeriesList) ( points := make([]Point, 0) for i, item := range series.Data { h := yRange.getRestHeight(item.Value) + if item.Value == nullValue { + h = math.MaxInt + } p := Point{ X: xValues[i], Y: h, diff --git a/painter.go b/painter.go index 1a954e2..f172cb3 100644 --- a/painter.go +++ b/painter.go @@ -438,11 +438,18 @@ func (p *Painter) MeasureTextMaxWidthHeight(textList []string) (int, int) { } func (p *Painter) LineStroke(points []Point) *Painter { + shouldMoveTo := false for index, point := range points { x := point.X y := point.Y - if index == 0 { + if y == math.MaxInt { + p.Stroke() + shouldMoveTo = true + continue + } + if shouldMoveTo || index == 0 { p.MoveTo(x, y) + shouldMoveTo = false } else { p.LineTo(x, y) } diff --git a/series.go b/series.go index ea71869..7bd6834 100644 --- a/series.go +++ b/series.go @@ -165,6 +165,10 @@ func (sl SeriesList) GetMaxMin(axisIndex int) (float64, float64) { continue } for _, item := range series.Data { + // 如果为空值,忽略 + if item.Value == nullValue { + continue + } if item.Value > max { max = item.Value }