From 7bb82ae691ee9631381b23828c9fac5f6ee1828b Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Sat, 9 Jul 2016 20:14:11 -0700 Subject: [PATCH 1/5] updates --- chart.go | 215 +++++++++++-------------------------------- continuous_series.go | 70 ++++++++++++++ defaults.go | 18 ++-- series.go | 192 +++++++++++++++++++------------------- time_series.go | 66 +++++++++++++ time_series_test.go | 30 ++++++ 6 files changed, 324 insertions(+), 267 deletions(-) create mode 100644 continuous_series.go create mode 100644 time_series.go create mode 100644 time_series_test.go diff --git a/chart.go b/chart.go index d8a5a19..8afaef1 100644 --- a/chart.go +++ b/chart.go @@ -17,10 +17,9 @@ type Chart struct { Height int DPI float64 - Background Style - Canvas Style - Axes Style - FinalValueLabel Style + Background Style + Canvas Style + Axes Style XRange Range YRange Range @@ -53,21 +52,20 @@ func (c Chart) GetFont() (*truetype.Font, error) { } // Render renders the chart with the given renderer to the given io.Writer. -func (c *Chart) Render(provider RendererProvider, w io.Writer) error { +func (c *Chart) Render(rp RendererProvider, w io.Writer) error { if len(c.Series) == 0 { return errors.New("Please provide at least one series") } - r, err := provider(c.Width, c.Height) + r, err := rp(c.Width, c.Height) if err != nil { return err } - if c.hasText() { - font, err := c.GetFont() - if err != nil { - return err - } - r.SetFont(font) + + font, err := c.GetFont() + if err != nil { + return err } + r.SetFont(font) r.SetDPI(c.GetDPI(DefaultDPI)) canvasBox := c.calculateCanvasBox(r) @@ -77,16 +75,12 @@ func (c *Chart) Render(provider RendererProvider, w io.Writer) error { c.drawCanvas(r, canvasBox) c.drawAxes(r, canvasBox, xrange, yrange) for index, series := range c.Series { - c.drawSeries(r, canvasBox, index, series, xrange, yrange) + c.drawSeries(r, canvasBox, series, xrange, yrange) } c.drawTitle(r) return r.Save(w) } -func (c Chart) hasText() bool { - return c.TitleStyle.Show || c.Axes.Show || c.FinalValueLabel.Show -} - func (c Chart) getAxisWidth() int { asw := 0 if c.Axes.Show { @@ -119,21 +113,19 @@ func (c Chart) calculateCanvasBox(r Renderer) Box { } func (c Chart) calculateFinalLabelWidth(r Renderer) int { - if !c.FinalValueLabel.Show { - return 0 - } - var finalLabelText string for _, s := range c.Series { - _, lv := s.GetValue(s.Len() - 1) - var ll string - if c.YRange.Formatter != nil { - ll = c.YRange.Formatter(lv) - } else { - ll = s.GetYFormatter()(lv) - } - if len(finalLabelText) < len(ll) { - finalLabelText = ll + if vs, isValueProvider := s.(ValueProvider); isValueProvider { + _, lv := vs.GetValue(vs.Len() - 1) + var ll string + if c.YRange.Formatter != nil { + ll = c.YRange.Formatter(lv) + } else if fp, isFormatterProvider := s.(FormatterProvider); isFormatterProvider { + ll = fp.GetYFormatter()(lv) + } + if len(finalLabelText) < len(ll) { + finalLabelText = ll + } } } @@ -145,7 +137,7 @@ func (c Chart) calculateFinalLabelWidth(r Renderer) int { pr := c.FinalValueLabel.Padding.GetRight(DefaultFinalLabelPadding.Right) lsw := int(c.FinalValueLabel.GetStrokeWidth(DefaultAxisLineWidth)) - return DefaultFinalLabelDeltaWidth + + return DefaultYAxisMargin + pl + pr + textWidth + asw + 2*lsw } @@ -163,33 +155,37 @@ func (c Chart) initRanges(canvasBox Box) (xrange Range, yrange Range) { var globalMinY, globalMinX float64 var globalMaxY, globalMaxX float64 for _, s := range c.Series { - seriesLength := s.Len() - for index := 0; index < seriesLength; index++ { - vx, vy := s.GetValue(index) - if didSetFirstValues { - if globalMinX > vx { - globalMinX = vx + if vp, isValueProvider := s.(ValueProvider); isValueProvider { + seriesLength := vp.Len() + for index := 0; index < seriesLength; index++ { + vx, vy := vp.GetValue(index) + if didSetFirstValues { + if globalMinX > vx { + globalMinX = vx + } + if globalMinY > vy { + globalMinY = vy + } + if globalMaxX < vx { + globalMaxX = vx + } + if globalMaxY < vy { + globalMaxY = vy + } + } else { + globalMinX, globalMaxX = vx, vx + globalMinY, globalMaxY = vy, vy + didSetFirstValues = true } - if globalMinY > vy { - globalMinY = vy - } - if globalMaxX < vx { - globalMaxX = vx - } - if globalMaxY < vy { - globalMaxY = vy - } - } else { - globalMinX, globalMaxX = vx, vx - globalMinY, globalMaxY = vy, vy - didSetFirstValues = true } } - if xrange.Formatter == nil { - xrange.Formatter = s.GetXFormatter() - } - if yrange.Formatter == nil { - yrange.Formatter = s.GetYFormatter() + if fp, isFormatterProvider := s.(FormatterProvider); isFormatterProvider { + if xrange.Formatter == nil { + xrange.Formatter = fp.GetXFormatter() + } + if yrange.Formatter == nil { + yrange.Formatter = fp.GetYFormatter() + } } } @@ -281,7 +277,7 @@ func (c Chart) generateRangeTicks(r Range, tickCount int, offset float64) []Tick func (c Chart) drawYAxisLabels(r Renderer, canvasBox Box, yrange Range) { tickFontSize := c.Axes.GetFontSize(DefaultAxisFontSize) asw := c.getAxisWidth() - tx := canvasBox.Right + DefaultFinalLabelDeltaWidth + asw + tx := canvasBox.Right + DefaultYAxisMargin + asw r.SetFontColor(c.Axes.GetFontColor(DefaultAxisColor)) r.SetFontSize(tickFontSize) @@ -332,111 +328,8 @@ func (c Chart) drawXAxisLabels(r Renderer, canvasBox Box, xrange Range) { } } -func (c Chart) drawSeries(r Renderer, canvasBox Box, index int, s Series, xrange, yrange Range) { - if s.Len() == 0 { - return - } - - cx := canvasBox.Left - cy := canvasBox.Top - cb := canvasBox.Bottom - cw := canvasBox.Width - - v0x, v0y := s.GetValue(0) - x0 := cw - xrange.Translate(v0x) - y0 := yrange.Translate(v0y) - - var vx, vy float64 - var x, y int - - fill := s.GetStyle().GetFillColor() - if !fill.IsZero() { - r.SetFillColor(fill) - r.MoveTo(x0+cx, y0+cy) - for i := 1; i < s.Len(); i++ { - vx, vy = s.GetValue(i) - x = cw - xrange.Translate(vx) - y = yrange.Translate(vy) - r.LineTo(x+cx, y+cy) - } - r.LineTo(x+cx, cb) - r.LineTo(x0+cx, cb) - r.Close() - r.Fill() - } - - stroke := s.GetStyle().GetStrokeColor(GetDefaultSeriesStrokeColor(index)) - r.SetStrokeColor(stroke) - r.SetStrokeWidth(s.GetStyle().GetStrokeWidth(DefaultStrokeWidth)) - - r.MoveTo(x0+cx, y0+cy) - for i := 1; i < s.Len(); i++ { - vx, vy = s.GetValue(i) - x = cw - xrange.Translate(vx) - y = yrange.Translate(vy) - r.LineTo(x+cx, y+cy) - } - r.Stroke() - - c.drawFinalValueLabel(r, canvasBox, index, s, yrange) -} - -func (c Chart) drawFinalValueLabel(r Renderer, canvasBox Box, index int, s Series, yrange Range) { - if c.FinalValueLabel.Show { - _, lv := s.GetValue(s.Len() - 1) - ll := yrange.Format(lv) - - py := canvasBox.Top - ly := yrange.Translate(lv) + py - - r.SetFontSize(c.FinalValueLabel.GetFontSize(DefaultFinalLabelFontSize)) - textWidth, _ := r.MeasureText(ll) - textHeight := int(math.Floor(DefaultFinalLabelFontSize)) - halfTextHeight := textHeight >> 1 - - asw := 0 - if c.Axes.Show { - asw = int(c.Axes.GetStrokeWidth(DefaultAxisLineWidth)) - } - - cx := canvasBox.Right + asw - - pt := c.FinalValueLabel.Padding.GetTop(DefaultFinalLabelPadding.Top) - pl := c.FinalValueLabel.Padding.GetLeft(DefaultFinalLabelPadding.Left) - pr := c.FinalValueLabel.Padding.GetRight(DefaultFinalLabelPadding.Right) - pb := c.FinalValueLabel.Padding.GetBottom(DefaultFinalLabelPadding.Bottom) - - textX := cx + pl + DefaultFinalLabelDeltaWidth - textY := ly + halfTextHeight - - ltlx := cx + pl + DefaultFinalLabelDeltaWidth - ltly := ly - (pt + halfTextHeight) - - ltrx := cx + pl + pr + textWidth - ltry := ly - (pt + halfTextHeight) - - lbrx := cx + pl + pr + textWidth - lbry := ly + (pb + halfTextHeight) - - lblx := cx + DefaultFinalLabelDeltaWidth - lbly := ly + (pb + halfTextHeight) - - //draw the shape... - r.SetFillColor(c.FinalValueLabel.GetFillColor(DefaultFinalLabelBackgroundColor)) - r.SetStrokeColor(c.FinalValueLabel.GetStrokeColor(s.GetStyle().GetStrokeColor(GetDefaultSeriesStrokeColor(index)))) - r.SetStrokeWidth(c.FinalValueLabel.GetStrokeWidth(DefaultAxisLineWidth)) - r.MoveTo(cx, ly) - r.LineTo(ltlx, ltly) - r.LineTo(ltrx, ltry) - r.LineTo(lbrx, lbry) - r.LineTo(lblx, lbly) - r.LineTo(cx, ly) - r.Close() - r.FillStroke() - - r.SetFontColor(c.FinalValueLabel.GetFontColor(DefaultTextColor)) - r.Text(ll, textX, textY) - } +func (c Chart) drawSeries(r Renderer, canvasBox Box, s Series, xrange, yrange Range) { + return s.Render(&c, r, canvasBox, xrange, yrange) } func (c Chart) drawTitle(r Renderer) error { diff --git a/continuous_series.go b/continuous_series.go new file mode 100644 index 0000000..f64ffb8 --- /dev/null +++ b/continuous_series.go @@ -0,0 +1,70 @@ +package chart + +import ( + "fmt" + + "github.com/blendlabs/go-util" +) + +// ContinuousSeries represents a line on a chart. +type ContinuousSeries struct { + Name string + Style Style + FinalValueLabel Style + + XValues []float64 + YValues []float64 +} + +// GetName returns the name of the time series. +func (cs ContinuousSeries) GetName() string { + return cs.Name +} + +// GetStyle returns the line style. +func (cs ContinuousSeries) GetStyle() Style { + return cs.Style +} + +// Len returns the number of elements in the series. +func (cs ContinuousSeries) Len() int { + return len(cs.XValues) +} + +// GetValue gets a value at a given index. +func (cs ContinuousSeries) GetValue(index int) (float64, float64) { + return cs.XValues[index], cs.YValues[index] +} + +// GetXFormatter returns the xs value formatter. +func (cs ContinuousSeries) GetXFormatter() Formatter { + return func(v interface{}) string { + if typed, isTyped := v.(float64); isTyped { + return fmt.Sprintf("%0.2f", typed) + } + return util.StringEmpty + } +} + +// GetYFormatter returns the y value formatter. +func (cs ContinuousSeries) GetYFormatter() Formatter { + return cs.GetXFormatter() +} + +// Render renders the series. +func (cs ContinuousSeries) Render(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range) error { + DrawLineSeries(c, r, canvasBox, xrange, yrange, cs) + + if cs.FinalValueLabel.Show { + asw := 0 + if c.Axes.Show { + asw = int(c.Axes.GetStrokeWidth(DefaultAxisLineWidth)) + } + + _, lv := cs.GetValue(cs.Len() - 1) + ll := yrange.Format(lv) + lx := canvasBox.Right + asw + ly := yrange.Translate(lv) + canvasBox.Top + DrawAnnotation(c, r, canvasBox, xrange, yrange, cs.FinalValueLabel, lx, ly, ll) + } +} diff --git a/defaults.go b/defaults.go index 0910ddf..b51df5e 100644 --- a/defaults.go +++ b/defaults.go @@ -24,14 +24,16 @@ const ( DefaultFontSize = 10.0 // DefaultTitleFontSize is the default title font size. DefaultTitleFontSize = 18.0 - // DefaultFinalLabelDeltaWidth is the width of the left triangle out of the final label. - DefaultFinalLabelDeltaWidth = 10 - // DefaultFinalLabelFontSize is the font size of the final label. - DefaultFinalLabelFontSize = 10.0 + // DefaultAnnotationDeltaWidth is the width of the left triangle out of annotations. + DefaultAnnotationDeltaWidth = 10 + // DefaultAnnotationFontSize is the font size of annotations. + DefaultAnnotationFontSize = 10.0 // DefaultAxisFontSize is the font size of the axis labels. DefaultAxisFontSize = 10.0 // DefaultTitleTop is the default distance from the top of the chart to put the title. DefaultTitleTop = 10 + // DefaultYAxisMargin is the default distance from the right of the canvas to the y axis labels. + DefaultYAxisMargin = 5 // DefaultXAxisMargin is the default distance from bottom of the canvas to the x axis labels. DefaultXAxisMargin = 10 // DefaultMinimumTickHorizontalSpacing is the minimum distance between horizontal ticks. @@ -69,8 +71,8 @@ var ( // DefaultFillColor is the default fill color. // It is equivalent to #0074d9. DefaultFillColor = drawing.Color{R: 0, G: 217, B: 116, A: 255} - // DefaultFinalLabelBackgroundColor is the default final label background color. - DefaultFinalLabelBackgroundColor = drawing.Color{R: 255, G: 255, B: 255, A: 255} + // DefaultAnnotationFillColor is the default annotation background color. + DefaultAnnotationFillColor = drawing.Color{R: 255, G: 255, B: 255, A: 255} ) var ( @@ -90,8 +92,8 @@ func GetDefaultSeriesStrokeColor(index int) drawing.Color { } var ( - // DefaultFinalLabelPadding is the padding around the final label. - DefaultFinalLabelPadding = Box{Top: 5, Left: 0, Right: 7, Bottom: 5} + // DefaultAnnotationPadding is the padding around an annotation. + DefaultAnnotationPadding = Box{Top: 5, Left: 0, Right: 7, Bottom: 5} // DefaultBackgroundPadding is the default canvas padding config. DefaultBackgroundPadding = Box{Top: 5, Left: 5, Right: 5, Bottom: 5} ) diff --git a/series.go b/series.go index 2851993..0b4d04c 100644 --- a/series.go +++ b/series.go @@ -1,121 +1,117 @@ package chart -import ( - "fmt" - "time" +import "math" - "github.com/blendlabs/go-util" -) - -// Series is a entity data set. +// Series is a entity data set. It constitutes an item to draw on the chart. +// The series interface is the bare minimum you need to implement to draw something on a chart. type Series interface { GetName() string GetStyle() Style + Render(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range) error +} + +// ValueProvider is a series that is a set of values. +type ValueProvider interface { Len() int - GetValue(index int) (float64, float64) +} +// FormatterProvider is a series that has custom formatters. +type FormatterProvider interface { GetXFormatter() Formatter GetYFormatter() Formatter } -// TimeSeries is a line on a chart. -type TimeSeries struct { - Name string - Style Style - - XValues []time.Time - YValues []float64 -} - -// GetName returns the name of the time series. -func (ts TimeSeries) GetName() string { - return ts.Name -} - -// GetStyle returns the line style. -func (ts TimeSeries) GetStyle() Style { - return ts.Style -} - -// Len returns the number of elements in the series. -func (ts TimeSeries) Len() int { - return len(ts.XValues) -} - -// GetValue gets a value at a given index. -func (ts TimeSeries) GetValue(index int) (x float64, y float64) { - x = float64(ts.XValues[index].Unix()) - y = ts.YValues[index] - return -} - -// GetXFormatter returns the x value formatter. -func (ts TimeSeries) GetXFormatter() Formatter { - return func(v interface{}) string { - if typed, isTyped := v.(time.Time); isTyped { - return typed.Format(DefaultDateFormat) - } - if typed, isTyped := v.(int64); isTyped { - return time.Unix(typed, 0).Format(DefaultDateFormat) - } - if typed, isTyped := v.(float64); isTyped { - return time.Unix(int64(typed), 0).Format(DefaultDateFormat) - } - return util.StringEmpty +// DrawLineSeries draws a line series with a renderer. +func DrawLineSeries(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range, vs ValueProvider) error { + if vs.Len() == 0 { + return } -} -// GetYFormatter returns the y value formatter. -func (ts TimeSeries) GetYFormatter() Formatter { - return func(v interface{}) string { - if typed, isTyped := v.(float64); isTyped { - return fmt.Sprintf("%0.2f", typed) + cx := canvasBox.Left + cy := canvasBox.Top + cb := canvasBox.Bottom + cw := canvasBox.Width + + v0x, v0y := vs.GetValue(0) + x0 := cw - xrange.Translate(v0x) + y0 := yrange.Translate(v0y) + + var vx, vy float64 + var x, y int + + fill := s.GetStyle().GetFillColor() + if !fill.IsZero() { + r.SetFillColor(fill) + r.MoveTo(x0+cx, y0+cy) + for i := 1; i < vs.Len(); i++ { + vx, vy = vs.GetValue(i) + x = cw - xrange.Translate(vx) + y = yrange.Translate(vy) + r.LineTo(x+cx, y+cy) } - return util.StringEmpty + r.LineTo(x+cx, cb) + r.LineTo(x0+cx, cb) + r.Close() + r.Fill() } -} -// ContinuousSeries represents a line on a chart. -type ContinuousSeries struct { - Name string - Style Style + stroke := s.GetStyle().GetStrokeColor(GetDefaultSeriesStrokeColor(index)) + r.SetStrokeColor(stroke) + r.SetStrokeWidth(s.GetStyle().GetStrokeWidth(DefaultStrokeWidth)) - XValues []float64 - YValues []float64 -} - -// GetName returns the name of the time series. -func (cs ContinuousSeries) GetName() string { - return cs.Name -} - -// GetStyle returns the line style. -func (cs ContinuousSeries) GetStyle() Style { - return cs.Style -} - -// Len returns the number of elements in the series. -func (cs ContinuousSeries) Len() int { - return len(cs.XValues) -} - -// GetValue gets a value at a given index. -func (cs ContinuousSeries) GetValue(index int) (float64, float64) { - return cs.XValues[index], cs.YValues[index] -} - -// GetXFormatter returns the xs value formatter. -func (cs ContinuousSeries) GetXFormatter() Formatter { - return func(v interface{}) string { - if typed, isTyped := v.(float64); isTyped { - return fmt.Sprintf("%0.2f", typed) - } - return util.StringEmpty + r.MoveTo(x0+cx, y0+cy) + for i := 1; i < vs.Len(); i++ { + vx, vy = vs.GetValue(i) + x = cw - xrange.Translate(vx) + y = yrange.Translate(vy) + r.LineTo(x+cx, y+cy) } + r.Stroke() } -// GetYFormatter returns the y value formatter. -func (cs ContinuousSeries) GetYFormatter() Formatter { - return cs.GetXFormatter() +// DrawAnnotation draws an anotation with a renderer. +func DrawAnnotation(c *Chart, r Renderer, canvasBox Box, xrange, yrange, s Style, lx, ly int, lv string) { + py := canvasBox.Top + + r.SetFontSize(s.GetFontSize(DefaultFinalLabelFontSize)) + textWidth, _ := r.MeasureText(ll) + textHeight := int(math.Floor(DefaultFinalLabelFontSize)) + halfTextHeight := textHeight >> 1 + + pt := s.Padding.GetTop(DefaultFinalLabelPadding.Top) + pl := s.Padding.GetLeft(DefaultFinalLabelPadding.Left) + pr := s.Padding.GetRight(DefaultFinalLabelPadding.Right) + pb := s.Padding.GetBottom(DefaultFinalLabelPadding.Bottom) + + textX := lx + pl + DefaultFinalLabelDeltaWidth + textY := ly + halfTextHeight + + ltlx := lx + pl + DefaultFinalLabelDeltaWidth + ltly := ly - (pt + halfTextHeight) + + ltrx := lx + pl + pr + textWidth + ltry := ly - (pt + halfTextHeight) + + lbrx := lx + pl + pr + textWidth + lbry := ly + (pb + halfTextHeight) + + lblx := lx + DefaultFinalLabelDeltaWidth + lbly := ly + (pb + halfTextHeight) + + //draw the shape... + r.SetFillColor(s.GetFillColor(DefaultAnnotationFillColor)) + r.SetStrokeColor(s.GetStrokeColor()) + r.SetStrokeWidth(s.GetStrokeWidth()) + r.MoveTo(lx, ly) + r.LineTo(ltlx, ltly) + r.LineTo(ltrx, ltry) + r.LineTo(lbrx, lbry) + r.LineTo(lblx, lbly) + r.LineTo(cx, ly) + r.Close() + r.FillStroke() + + r.SetFontColor(s.GetFontColor(DefaultTextColor)) + r.Text(ll, textX, textY) } diff --git a/time_series.go b/time_series.go new file mode 100644 index 0000000..fd02b29 --- /dev/null +++ b/time_series.go @@ -0,0 +1,66 @@ +package chart + +import ( + "fmt" + "time" + + "github.com/blendlabs/go-util" +) + +// TimeSeries is a line on a chart. +type TimeSeries struct { + Name string + Style Style + FinalValueLabel Style + + XValues []time.Time + YValues []float64 +} + +// GetName returns the name of the time series. +func (ts TimeSeries) GetName() string { + return ts.Name +} + +// GetStyle returns the line style. +func (ts TimeSeries) GetStyle() Style { + return ts.Style +} + +// Len returns the number of elements in the series. +func (ts TimeSeries) Len() int { + return len(ts.XValues) +} + +// GetValue gets a value at a given index. +func (ts TimeSeries) GetValue(index int) (x float64, y float64) { + x = float64(ts.XValues[index].Unix()) + y = ts.YValues[index] + return +} + +// GetXFormatter returns the x value formatter. +func (ts TimeSeries) GetXFormatter() Formatter { + return func(v interface{}) string { + if typed, isTyped := v.(time.Time); isTyped { + return typed.Format(DefaultDateFormat) + } + if typed, isTyped := v.(int64); isTyped { + return time.Unix(typed, 0).Format(DefaultDateFormat) + } + if typed, isTyped := v.(float64); isTyped { + return time.Unix(int64(typed), 0).Format(DefaultDateFormat) + } + return util.StringEmpty + } +} + +// GetYFormatter returns the y value formatter. +func (ts TimeSeries) GetYFormatter() Formatter { + return func(v interface{}) string { + if typed, isTyped := v.(float64); isTyped { + return fmt.Sprintf("%0.2f", typed) + } + return util.StringEmpty + } +} diff --git a/time_series_test.go b/time_series_test.go new file mode 100644 index 0000000..3194997 --- /dev/null +++ b/time_series_test.go @@ -0,0 +1,30 @@ +package chart + +import ( + "testing" + "time" + + "github.com/blendlabs/go-assert" +) + +func TestTimeSeriesGetValue(t *testing.T) { + assert := assert.New(t) + + ts := TimeSeries{ + Name: "Test", + XValues: []time.Time{ + time.Now().AddDate(0, 0, -5), + time.Now().AddDate(0, 0, -4), + time.Now().AddDate(0, 0, -3), + time.Now().AddDate(0, 0, -2), + time.Now().AddDate(0, 0, -1), + }, + YValues: []float64{ + 1.0, 2.0, 3.0, 4.0, 5.0, + }, + } + + x0, y0 := ts.GetValue(0) + assert.NotZero(x0) + assert.Equal(1.0, y0) +} From e9a36274acfc8ddb50427d6f200502c7ee9abd33 Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Sun, 10 Jul 2016 01:11:47 -0700 Subject: [PATCH 2/5] snapshot. --- annotation_series.go | 26 ++++ axis.go | 59 ++++++++ box.go | 2 +- chart.go | 329 ++++++++++++++++++------------------------- continuous_series.go | 46 +----- drawing_helpers.go | 95 +++++++++++++ formatter.go | 4 - range.go | 26 +--- raster_renderer.go | 5 + renderable.go | 6 + renderer.go | 6 +- renderer_provider.go | 4 + series.go | 116 +-------------- series_test.go | 30 ---- style.go | 52 ++++++- tick.go | 25 ++++ time_series.go | 47 ++----- util.go | 8 +- value_formatter.go | 43 ++++++ value_provider.go | 7 + vector_renderer.go | 5 + xaxis.go | 27 ++++ yaxis.go | 28 ++++ 23 files changed, 551 insertions(+), 445 deletions(-) create mode 100644 annotation_series.go create mode 100644 axis.go create mode 100644 drawing_helpers.go delete mode 100644 formatter.go create mode 100644 renderable.go create mode 100644 renderer_provider.go delete mode 100644 series_test.go create mode 100644 tick.go create mode 100644 value_formatter.go create mode 100644 value_provider.go create mode 100644 xaxis.go create mode 100644 yaxis.go diff --git a/annotation_series.go b/annotation_series.go new file mode 100644 index 0000000..a41aa58 --- /dev/null +++ b/annotation_series.go @@ -0,0 +1,26 @@ +package chart + +// Annotation is a label on the chart. +type Annotation struct { + X, Y float64 + Label string +} + +// AnnotationSeries is a series of labels on the chart. +type AnnotationSeries struct { + Name string + Style Style + YAxis YAxisType + Annotations []Annotation +} + +// Render draws the series. +func (as AnnotationSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range) { + if as.Style.Show { + for _, a := range as.Annotations { + lx := xrange.Translate(a.X) + canvasBox.Left + ly := yrange.Translate(a.Y) + canvasBox.Top + DrawAnnotation(r, canvasBox, xrange, yrange, as.Style, lx, ly, a.Label) + } + } +} diff --git a/axis.go b/axis.go new file mode 100644 index 0000000..1ce0e7c --- /dev/null +++ b/axis.go @@ -0,0 +1,59 @@ +package chart + +// YAxisType is a type of y-axis; it can either be primary or secondary. +type YAxisType int + +const ( + // YAxisPrimary is the primary axis. + YAxisPrimary YAxisType = 0 + // YAxisSecondary is the secondary axis. + YAxisSecondary YAxisType = 1 +) + +// Axis is a chart feature detailing what values happen where. +type Axis interface { + GetName() string + GetStyle() Style + Render(c *Chart, r Renderer, canvasBox Box, ra Range) +} + +// axis represents the basics of an axis implementation. +type axis struct { + Name string + Style Style + ValueFormatter ValueFormatter + Range Range + Ticks []Tick +} + +func (a axis) GetName() string { + return a.Name +} + +func (a axis) GetStyle() Style { + return a.Style +} + +func (a axis) getTicks(ra Range) []Tick { + if len(a.Ticks) > 0 { + return a.Ticks + } + return a.generateTicks(ra) +} + +func (a axis) generateTicks(ra Range) []Tick { + step := a.getTickStep(ra) + return a.generateTicksWithStep(ra, step) +} + +func (a axis) getTickCount(ra Range) int { + return 0 +} + +func (a axis) getTickStep(ra Range) float64 { + return 0.0 +} + +func (a axis) generateTicksWithStep(ra Range, step float64) []Tick { + return []Tick{} +} diff --git a/box.go b/box.go index 25358b1..5207569 100644 --- a/box.go +++ b/box.go @@ -20,7 +20,7 @@ func (b Box) IsZero() bool { // String returns a string representation of the box. func (b Box) String() string { - return fmt.Sprintf("Box(%d,%d,%d,%d)", b.Top, b.Left, b.Right, b.Bottom) + return fmt.Sprintf("box(%d,%d,%d,%d)", b.Top, b.Left, b.Right, b.Bottom) } // GetTop returns a coalesced value with a default. diff --git a/chart.go b/chart.go index 8afaef1..261d622 100644 --- a/chart.go +++ b/chart.go @@ -3,7 +3,6 @@ package chart import ( "errors" "io" - "math" "github.com/golang/freetype/truetype" ) @@ -19,10 +18,10 @@ type Chart struct { Background Style Canvas Style - Axes Style - XRange Range - YRange Range + XAxis XAxis + YAxis YAxis + YAxisSecondary YAxis Font *truetype.Font Series []Series @@ -68,92 +67,28 @@ func (c *Chart) Render(rp RendererProvider, w io.Writer) error { r.SetFont(font) r.SetDPI(c.GetDPI(DefaultDPI)) - canvasBox := c.calculateCanvasBox(r) - xrange, yrange := c.initRanges(canvasBox) + xrange, yrange, yrangeAlt := c.getRanges() + canvasBox := c.getCanvasBox(r, xrange, yrange, yrangeAlt) + xrange, yrange, yrangeAlt = c.getRangeDomains(canvasBox, xrange, yrange, yrangeAlt) c.drawBackground(r) c.drawCanvas(r, canvasBox) - c.drawAxes(r, canvasBox, xrange, yrange) + c.drawAxes(r, canvasBox, xrange, yrange, yrangeAlt) for index, series := range c.Series { - c.drawSeries(r, canvasBox, series, xrange, yrange) + c.drawSeries(r, canvasBox, xrange, yrange, yrangeAlt, series, index) } c.drawTitle(r) return r.Save(w) } -func (c Chart) getAxisWidth() int { - asw := 0 - if c.Axes.Show { - asw = int(c.Axes.GetStrokeWidth(DefaultAxisLineWidth)) - } - return asw -} - -func (c Chart) calculateCanvasBox(r Renderer) Box { - dpr := DefaultBackgroundPadding.Right - finalLabelWidth := c.calculateFinalLabelWidth(r) - if finalLabelWidth > dpr { - dpr = finalLabelWidth - } - axisBottomHeight := c.calculateBottomLabelHeight() - dpb := DefaultBackgroundPadding.Bottom - if dpb < axisBottomHeight { - dpb = axisBottomHeight - } - - cb := Box{ - Top: c.Background.Padding.GetTop(DefaultBackgroundPadding.Top), - Left: c.Background.Padding.GetLeft(DefaultBackgroundPadding.Left), - Right: c.Width - c.Background.Padding.GetRight(dpr), - Bottom: c.Height - c.Background.Padding.GetBottom(dpb), - } - cb.Height = cb.Bottom - cb.Top - cb.Width = cb.Right - cb.Left - return cb -} - -func (c Chart) calculateFinalLabelWidth(r Renderer) int { - var finalLabelText string - for _, s := range c.Series { - if vs, isValueProvider := s.(ValueProvider); isValueProvider { - _, lv := vs.GetValue(vs.Len() - 1) - var ll string - if c.YRange.Formatter != nil { - ll = c.YRange.Formatter(lv) - } else if fp, isFormatterProvider := s.(FormatterProvider); isFormatterProvider { - ll = fp.GetYFormatter()(lv) - } - if len(finalLabelText) < len(ll) { - finalLabelText = ll - } - } - } - - r.SetFontSize(c.FinalValueLabel.GetFontSize(DefaultFinalLabelFontSize)) - textWidth, _ := r.MeasureText(finalLabelText) - asw := c.getAxisWidth() - - pl := c.FinalValueLabel.Padding.GetLeft(DefaultFinalLabelPadding.Left) - pr := c.FinalValueLabel.Padding.GetRight(DefaultFinalLabelPadding.Right) - lsw := int(c.FinalValueLabel.GetStrokeWidth(DefaultAxisLineWidth)) - - return DefaultYAxisMargin + - pl + pr + - textWidth + asw + 2*lsw -} - -func (c Chart) calculateBottomLabelHeight() int { - if c.Axes.Show { - return c.getAxisWidth() + int(math.Ceil(c.Axes.GetFontSize(DefaultAxisFontSize))) + DefaultXAxisMargin - } - return 0 -} - -func (c Chart) initRanges(canvasBox Box) (xrange Range, yrange Range) { +func (c Chart) getRanges() (xrange, yrange, yrangeAlt Range) { //iterate over each series, pull out the min/max for x,y var didSetFirstValues bool - var globalMinY, globalMinX float64 - var globalMaxY, globalMaxX float64 + + var globalMinX, globalMaxX float64 + var globalMinY, globalMaxY float64 + var globalMinYA, globalMaxYA float64 + for _, s := range c.Series { if vp, isValueProvider := s.(ValueProvider); isValueProvider { seriesLength := vp.Len() @@ -163,65 +98,130 @@ func (c Chart) initRanges(canvasBox Box) (xrange Range, yrange Range) { if globalMinX > vx { globalMinX = vx } - if globalMinY > vy { - globalMinY = vy - } if globalMaxX < vx { globalMaxX = vx } - if globalMaxY < vy { - globalMaxY = vy + if s.GetYAxis() == YAxisPrimary { + if globalMinY > vy { + globalMinY = vy + } + if globalMaxY < vy { + globalMaxY = vy + } + } else if s.GetYAxis() == YAxisSecondary { + if globalMinYA > vy { + globalMinYA = vy + } + if globalMaxYA < vy { + globalMaxYA = vy + } } } else { globalMinX, globalMaxX = vx, vx - globalMinY, globalMaxY = vy, vy + if s.GetYAxis() == YAxisPrimary { + globalMinY, globalMaxY = vy, vy + } else if s.GetYAxis() == YAxisSecondary { + globalMinYA, globalMaxYA = vy, vy + } didSetFirstValues = true } } } - if fp, isFormatterProvider := s.(FormatterProvider); isFormatterProvider { - if xrange.Formatter == nil { - xrange.Formatter = fp.GetXFormatter() - } - if yrange.Formatter == nil { - yrange.Formatter = fp.GetYFormatter() - } - } } - if c.XRange.IsZero() { + if !c.XAxis.Range.IsZero() { + xrange.Min = c.XAxis.Range.Min + xrange.Max = c.XAxis.Range.Max + } else { xrange.Min = globalMinX xrange.Max = globalMaxX - } else { - xrange.Min = c.XRange.Min - xrange.Max = c.XRange.Max } - if c.XRange.Formatter != nil { - xrange.Formatter = c.XRange.Formatter - } - if c.XRange.Ticks != nil { - xrange.Ticks = c.XRange.Ticks - } - xrange.Domain = canvasBox.Width - if c.YRange.IsZero() { + if !c.YAxis.Range.IsZero() { + yrange.Min = c.YAxis.Range.Min + yrange.Max = c.YAxis.Range.Max + } else { yrange.Min = globalMinY yrange.Max = globalMaxY - } else { - yrange.Min = c.YRange.Min - yrange.Max = c.YRange.Max } - if c.YRange.Formatter != nil { - yrange.Formatter = c.YRange.Formatter - } - if c.YRange.Ticks != nil { - yrange.Ticks = c.YRange.Ticks - } - yrange.Domain = canvasBox.Height - return } +func (c Chart) getCanvasBox(r Renderer, xrange, yrange, yrangeAlt Range) Box { + dpl := c.Background.Padding.GetLeft(DefaultBackgroundPadding.Left) + dpr := c.Background.Padding.GetRight(DefaultBackgroundPadding.Right) + dpb := c.Background.Padding.GetBottom(DefaultBackgroundPadding.Bottom) + + if c.YAxisSecondary.Style.Show { + dpl = c.getYAxisSecondaryWidth(r, yrangeAlt) + } + if c.YAxis.Style.Show { + dpr = c.getYAxisWidth(r, yrange) + } + if c.XAxis.Style.Show { + dpb = c.getXAxisHeight(r, xrange) + } + + cb := Box{ + Top: c.Background.Padding.GetTop(DefaultBackgroundPadding.Top), + Left: dpl, + Right: c.Width - dpr, + Bottom: c.Height - dpb, + } + cb.Height = cb.Bottom - cb.Top + cb.Width = cb.Right - cb.Left + return cb +} + +func (c Chart) getYAxisSecondaryWidth(r Renderer, ra Range) int { + var ll string + ticks := c.YAxisSecondary.getTicks(ra) + for _, t := range ticks { + if len(t.Label) > len(ll) { + ll = t.Label + } + } + r.SetFontSize(c.YAxisSecondary.Style.GetFontSize(DefaultFontSize)) + r.SetFont(c.YAxisSecondary.Style.GetFont(c.Font)) + tw, _ := r.MeasureText(ll) + return tw + DefaultYAxisMargin +} + +func (c Chart) getYAxisWidth(r Renderer, ra Range) int { + var ll string + ticks := c.YAxis.getTicks(ra) + for _, t := range ticks { + if len(t.Label) > len(ll) { + ll = t.Label + } + } + r.SetFontSize(c.YAxis.Style.GetFontSize(DefaultFontSize)) + r.SetFont(c.YAxis.Style.GetFont(c.Font)) + tw, _ := r.MeasureText(ll) + return tw + DefaultYAxisMargin +} + +func (c Chart) getXAxisHeight(r Renderer, ra Range) int { + r.SetFontSize(c.XAxis.Style.GetFontSize(DefaultFontSize)) + r.SetFont(c.XAxis.Style.GetFont(c.Font)) + var tl int + ticks := c.YAxis.getTicks(ra) + for _, t := range ticks { + _, lh := r.MeasureText(t.Label) + if lh > tl { + tl = lh + } + } + return tl + DefaultXAxisMargin +} + +func (c Chart) getRangeDomains(canvasBox Box, xrange, yrange, yrangeAlt Range) (Range, Range, Range) { + xrange.Domain = canvasBox.Width + yrange.Domain = canvasBox.Height + yrangeAlt.Domain = canvasBox.Height + return xrange, yrange, yrangeAlt +} + func (c Chart) drawBackground(r Renderer) { r.SetFillColor(c.Background.GetFillColor(DefaultBackgroundColor)) r.SetStrokeColor(c.Background.GetStrokeColor(DefaultBackgroundStrokeColor)) @@ -248,88 +248,35 @@ func (c Chart) drawCanvas(r Renderer, canvasBox Box) { r.FillStroke() } -func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange Range) { - if c.Axes.Show { - r.SetStrokeColor(c.Axes.GetStrokeColor(DefaultAxisColor)) - r.SetStrokeWidth(c.Axes.GetStrokeWidth(DefaultStrokeWidth)) - r.MoveTo(canvasBox.Left, canvasBox.Bottom) - r.LineTo(canvasBox.Right, canvasBox.Bottom) - r.LineTo(canvasBox.Right, canvasBox.Top) - r.Stroke() - - c.drawXAxisLabels(r, canvasBox, xrange) - c.drawYAxisLabels(r, canvasBox, yrange) +func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range) { + if c.XAxis.Style.Show { + c.XAxis.Render(r, canvasBox, xrange) + } + if c.YAxis.Style.Show { + c.YAxis.Render(r, canvasBox, yrange, YAxisPrimary) + } + if c.YAxisSecondary.Style.Show { + c.YAxisSecondary.Render(r, canvasBox, yrangeAlt, YAxisSecondary) } } -func (c Chart) generateRangeTicks(r Range, tickCount int, offset float64) []Tick { - var ticks []Tick - rangeTicks := Slices(tickCount, r.Max-r.Min) - for _, rv := range rangeTicks { - ticks = append(ticks, Tick{ - RangeValue: rv + offset, - Label: r.Format(rv + offset), - }) - } - return ticks -} - -func (c Chart) drawYAxisLabels(r Renderer, canvasBox Box, yrange Range) { - tickFontSize := c.Axes.GetFontSize(DefaultAxisFontSize) - asw := c.getAxisWidth() - tx := canvasBox.Right + DefaultYAxisMargin + asw - - r.SetFontColor(c.Axes.GetFontColor(DefaultAxisColor)) - r.SetFontSize(tickFontSize) - - ticks := yrange.Ticks - if ticks == nil { - minimumTickHeight := tickFontSize + DefaultMinimumTickVerticalSpacing - tickCount := int(math.Floor(float64(yrange.Domain) / float64(minimumTickHeight))) - - if tickCount > DefaultMaxTickCount { - tickCount = DefaultMaxTickCount - } - ticks = c.generateRangeTicks(yrange, tickCount, yrange.Min) - } - - for _, t := range ticks { - v := t.RangeValue - y := yrange.Translate(v) - ty := int(y) - r.Text(t.Label, tx, ty) +func (c Chart) getSeriesDefaults(seriesIndex int) Style { + strokeColor := GetDefaultSeriesStrokeColor(seriesIndex) + return Style{ + StrokeColor: strokeColor, + StrokeWidth: DefaultStrokeWidth, + FillColor: strokeColor.WithAlpha(100), + Font: c.Font, + FontSize: DefaultFontSize, } } -func (c Chart) drawXAxisLabels(r Renderer, canvasBox Box, xrange Range) { - tickFontSize := c.Axes.GetFontSize(DefaultAxisFontSize) - ty := canvasBox.Bottom + DefaultXAxisMargin + int(tickFontSize) - - r.SetFontColor(c.Axes.GetFontColor(DefaultAxisColor)) - r.SetFontSize(tickFontSize) - - ticks := xrange.Ticks - if ticks == nil { - maxLabelWidth := 60 - minimumTickWidth := maxLabelWidth + DefaultMinimumTickHorizontalSpacing - tickCount := int(math.Floor(float64(xrange.Domain) / float64(minimumTickWidth))) - - if tickCount > DefaultMaxTickCount { - tickCount = DefaultMaxTickCount - } - ticks = c.generateRangeTicks(xrange, tickCount, xrange.Min) +func (c Chart) drawSeries(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range, s Series, seriesIndex int) { + if s.GetYAxis() == YAxisPrimary { + s.Render(r, canvasBox, xrange, yrange, c.getSeriesDefaults(seriesIndex)) + } else if s.GetYAxis() == YAxisSecondary { + s.Render(r, canvasBox, xrange, yrange, c.getSeriesDefaults(seriesIndex)) } - - for _, t := range ticks { - v := t.RangeValue - x := xrange.Translate(v) - tx := canvasBox.Left + int(x) - r.Text(t.Label, tx, ty) - } -} - -func (c Chart) drawSeries(r Renderer, canvasBox Box, s Series, xrange, yrange Range) { - return s.Render(&c, r, canvasBox, xrange, yrange) } func (c Chart) drawTitle(r Renderer) error { diff --git a/continuous_series.go b/continuous_series.go index f64ffb8..b399727 100644 --- a/continuous_series.go +++ b/continuous_series.go @@ -1,16 +1,11 @@ package chart -import ( - "fmt" - - "github.com/blendlabs/go-util" -) - // ContinuousSeries represents a line on a chart. type ContinuousSeries struct { - Name string - Style Style - FinalValueLabel Style + Name string + Style Style + + YAxis YAxisType XValues []float64 YValues []float64 @@ -36,35 +31,8 @@ func (cs ContinuousSeries) GetValue(index int) (float64, float64) { return cs.XValues[index], cs.YValues[index] } -// GetXFormatter returns the xs value formatter. -func (cs ContinuousSeries) GetXFormatter() Formatter { - return func(v interface{}) string { - if typed, isTyped := v.(float64); isTyped { - return fmt.Sprintf("%0.2f", typed) - } - return util.StringEmpty - } -} - -// GetYFormatter returns the y value formatter. -func (cs ContinuousSeries) GetYFormatter() Formatter { - return cs.GetXFormatter() -} - // Render renders the series. -func (cs ContinuousSeries) Render(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range) error { - DrawLineSeries(c, r, canvasBox, xrange, yrange, cs) - - if cs.FinalValueLabel.Show { - asw := 0 - if c.Axes.Show { - asw = int(c.Axes.GetStrokeWidth(DefaultAxisLineWidth)) - } - - _, lv := cs.GetValue(cs.Len() - 1) - ll := yrange.Format(lv) - lx := canvasBox.Right + asw - ly := yrange.Translate(lv) + canvasBox.Top - DrawAnnotation(c, r, canvasBox, xrange, yrange, cs.FinalValueLabel, lx, ly, ll) - } +func (cs ContinuousSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { + style := cs.Style.WithDefaultsFrom(defaults) + DrawLineSeries(r, canvasBox, xrange, yrange, style, cs) } diff --git a/drawing_helpers.go b/drawing_helpers.go new file mode 100644 index 0000000..0fcff3d --- /dev/null +++ b/drawing_helpers.go @@ -0,0 +1,95 @@ +package chart + +import "math" + +// DrawLineSeries draws a line series with a renderer. +func DrawLineSeries(r Renderer, canvasBox Box, xrange, yrange Range, s Style, vs ValueProvider) { + if vs.Len() == 0 { + return + } + + cx := canvasBox.Left + cy := canvasBox.Top + cb := canvasBox.Bottom + cw := canvasBox.Width + + v0x, v0y := vs.GetValue(0) + x0 := cw - xrange.Translate(v0x) + y0 := yrange.Translate(v0y) + + var vx, vy float64 + var x, y int + + fill := s.GetFillColor() + if !fill.IsZero() { + r.SetFillColor(fill) + r.MoveTo(x0+cx, y0+cy) + for i := 1; i < vs.Len(); i++ { + vx, vy = vs.GetValue(i) + x = cw - xrange.Translate(vx) + y = yrange.Translate(vy) + r.LineTo(x+cx, y+cy) + } + r.LineTo(x+cx, cb) + r.LineTo(x0+cx, cb) + r.Close() + r.Fill() + } + + stroke := s.GetStrokeColor() + r.SetStrokeColor(stroke) + r.SetStrokeWidth(s.GetStrokeWidth(DefaultStrokeWidth)) + + r.MoveTo(x0+cx, y0+cy) + for i := 1; i < vs.Len(); i++ { + vx, vy = vs.GetValue(i) + x = cw - xrange.Translate(vx) + y = yrange.Translate(vy) + r.LineTo(x+cx, y+cy) + } + r.Stroke() +} + +// DrawAnnotation draws an anotation with a renderer. +func DrawAnnotation(r Renderer, canvasBox Box, xrange, yrange Range, s Style, lx, ly int, label string) { + r.SetFontSize(s.GetFontSize(DefaultAnnotationFontSize)) + textWidth, _ := r.MeasureText(label) + textHeight := int(math.Floor(DefaultAnnotationFontSize)) + halfTextHeight := textHeight >> 1 + + pt := s.Padding.GetTop(DefaultAnnotationPadding.Top) + pl := s.Padding.GetLeft(DefaultAnnotationPadding.Left) + pr := s.Padding.GetRight(DefaultAnnotationPadding.Right) + pb := s.Padding.GetBottom(DefaultAnnotationPadding.Bottom) + + textX := lx + pl + DefaultAnnotationDeltaWidth + textY := ly + halfTextHeight + + ltlx := lx + pl + DefaultAnnotationDeltaWidth + ltly := ly - (pt + halfTextHeight) + + ltrx := lx + pl + pr + textWidth + ltry := ly - (pt + halfTextHeight) + + lbrx := lx + pl + pr + textWidth + lbry := ly + (pb + halfTextHeight) + + lblx := lx + DefaultAnnotationDeltaWidth + lbly := ly + (pb + halfTextHeight) + + //draw the shape... + r.SetFillColor(s.GetFillColor(DefaultAnnotationFillColor)) + r.SetStrokeColor(s.GetStrokeColor()) + r.SetStrokeWidth(s.GetStrokeWidth()) + r.MoveTo(lx, ly) + r.LineTo(ltlx, ltly) + r.LineTo(ltrx, ltry) + r.LineTo(lbrx, lbry) + r.LineTo(lblx, lbly) + r.LineTo(lx, ly) + r.Close() + r.FillStroke() + + r.SetFontColor(s.GetFontColor(DefaultTextColor)) + r.Text(label, textX, textY) +} diff --git a/formatter.go b/formatter.go deleted file mode 100644 index b1eda07..0000000 --- a/formatter.go +++ /dev/null @@ -1,4 +0,0 @@ -package chart - -// Formatter is a function that takes a value and produces a string. -type Formatter func(v interface{}) string diff --git a/range.go b/range.go index d3ab4a7..513427d 100644 --- a/range.go +++ b/range.go @@ -3,23 +3,13 @@ package chart import ( "fmt" "math" - - "github.com/blendlabs/go-util" ) -// Tick represents a label on an axis. -type Tick struct { - RangeValue float64 - Label string -} - -// Range represents a continuous range, +// Range represents a boundary for a set of numbers. type Range struct { - Min float64 - Max float64 - Domain int - Ticks []Tick - Formatter Formatter + Min float64 + Max float64 + Domain int } // IsZero returns if the range has been set or not. @@ -37,14 +27,6 @@ func (r Range) String() string { return fmt.Sprintf("Range [%.2f,%.2f] => %d", r.Min, r.Max, r.Domain) } -// Format formats the value based on the range's formatter. -func (r Range) Format(v interface{}) string { - if r.Formatter != nil { - return r.Formatter(v) - } - return util.StringEmpty -} - // Translate maps a given value into the range space. // An example would be a 600 px image, with a min of 10 and a max of 100. // Translate(50) would yield (50.0/90.0)*600 ~= 333.33 diff --git a/raster_renderer.go b/raster_renderer.go index 88b29ef..4f0e0cc 100644 --- a/raster_renderer.go +++ b/raster_renderer.go @@ -33,6 +33,11 @@ type rasterRenderer struct { f *truetype.Font } +// GetDPI returns the dpi. +func (rr *rasterRenderer) GetDPI() float64 { + return rr.gc.GetDPI() +} + // SetDPI implements the interface method. func (rr *rasterRenderer) SetDPI(dpi float64) { rr.gc.SetDPI(dpi) diff --git a/renderable.go b/renderable.go new file mode 100644 index 0000000..8216685 --- /dev/null +++ b/renderable.go @@ -0,0 +1,6 @@ +package chart + +// Renderable is a type that can be rendered onto a chart. +type Renderable interface { + Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) +} diff --git a/renderer.go b/renderer.go index 5a7c367..cf0c0f4 100644 --- a/renderer.go +++ b/renderer.go @@ -7,11 +7,11 @@ import ( "github.com/wcharczuk/go-chart/drawing" ) -// RendererProvider is a function that returns a renderer. -type RendererProvider func(int, int) (Renderer, error) - // Renderer represents the basic methods required to draw a chart. type Renderer interface { + // GetDPI returns the dpi for the renderer. + GetDPI() float64 + // SetDPI sets the DPI for the renderer. SetDPI(dpi float64) diff --git a/renderer_provider.go b/renderer_provider.go new file mode 100644 index 0000000..be961a8 --- /dev/null +++ b/renderer_provider.go @@ -0,0 +1,4 @@ +package chart + +// RendererProvider is a function that returns a renderer. +type RendererProvider func(int, int) (Renderer, error) diff --git a/series.go b/series.go index 0b4d04c..af75d5e 100644 --- a/series.go +++ b/series.go @@ -1,117 +1,7 @@ package chart -import "math" - -// Series is a entity data set. It constitutes an item to draw on the chart. -// The series interface is the bare minimum you need to implement to draw something on a chart. +// Series is an alias to Renderable. type Series interface { - GetName() string - GetStyle() Style - Render(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range) error -} - -// ValueProvider is a series that is a set of values. -type ValueProvider interface { - Len() int - GetValue(index int) (float64, float64) -} - -// FormatterProvider is a series that has custom formatters. -type FormatterProvider interface { - GetXFormatter() Formatter - GetYFormatter() Formatter -} - -// DrawLineSeries draws a line series with a renderer. -func DrawLineSeries(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range, vs ValueProvider) error { - if vs.Len() == 0 { - return - } - - cx := canvasBox.Left - cy := canvasBox.Top - cb := canvasBox.Bottom - cw := canvasBox.Width - - v0x, v0y := vs.GetValue(0) - x0 := cw - xrange.Translate(v0x) - y0 := yrange.Translate(v0y) - - var vx, vy float64 - var x, y int - - fill := s.GetStyle().GetFillColor() - if !fill.IsZero() { - r.SetFillColor(fill) - r.MoveTo(x0+cx, y0+cy) - for i := 1; i < vs.Len(); i++ { - vx, vy = vs.GetValue(i) - x = cw - xrange.Translate(vx) - y = yrange.Translate(vy) - r.LineTo(x+cx, y+cy) - } - r.LineTo(x+cx, cb) - r.LineTo(x0+cx, cb) - r.Close() - r.Fill() - } - - stroke := s.GetStyle().GetStrokeColor(GetDefaultSeriesStrokeColor(index)) - r.SetStrokeColor(stroke) - r.SetStrokeWidth(s.GetStyle().GetStrokeWidth(DefaultStrokeWidth)) - - r.MoveTo(x0+cx, y0+cy) - for i := 1; i < vs.Len(); i++ { - vx, vy = vs.GetValue(i) - x = cw - xrange.Translate(vx) - y = yrange.Translate(vy) - r.LineTo(x+cx, y+cy) - } - r.Stroke() -} - -// DrawAnnotation draws an anotation with a renderer. -func DrawAnnotation(c *Chart, r Renderer, canvasBox Box, xrange, yrange, s Style, lx, ly int, lv string) { - py := canvasBox.Top - - r.SetFontSize(s.GetFontSize(DefaultFinalLabelFontSize)) - textWidth, _ := r.MeasureText(ll) - textHeight := int(math.Floor(DefaultFinalLabelFontSize)) - halfTextHeight := textHeight >> 1 - - pt := s.Padding.GetTop(DefaultFinalLabelPadding.Top) - pl := s.Padding.GetLeft(DefaultFinalLabelPadding.Left) - pr := s.Padding.GetRight(DefaultFinalLabelPadding.Right) - pb := s.Padding.GetBottom(DefaultFinalLabelPadding.Bottom) - - textX := lx + pl + DefaultFinalLabelDeltaWidth - textY := ly + halfTextHeight - - ltlx := lx + pl + DefaultFinalLabelDeltaWidth - ltly := ly - (pt + halfTextHeight) - - ltrx := lx + pl + pr + textWidth - ltry := ly - (pt + halfTextHeight) - - lbrx := lx + pl + pr + textWidth - lbry := ly + (pb + halfTextHeight) - - lblx := lx + DefaultFinalLabelDeltaWidth - lbly := ly + (pb + halfTextHeight) - - //draw the shape... - r.SetFillColor(s.GetFillColor(DefaultAnnotationFillColor)) - r.SetStrokeColor(s.GetStrokeColor()) - r.SetStrokeWidth(s.GetStrokeWidth()) - r.MoveTo(lx, ly) - r.LineTo(ltlx, ltly) - r.LineTo(ltrx, ltry) - r.LineTo(lbrx, lbry) - r.LineTo(lblx, lbly) - r.LineTo(cx, ly) - r.Close() - r.FillStroke() - - r.SetFontColor(s.GetFontColor(DefaultTextColor)) - r.Text(ll, textX, textY) + GetYAxis() YAxisType + Renderable } diff --git a/series_test.go b/series_test.go deleted file mode 100644 index 3194997..0000000 --- a/series_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package chart - -import ( - "testing" - "time" - - "github.com/blendlabs/go-assert" -) - -func TestTimeSeriesGetValue(t *testing.T) { - assert := assert.New(t) - - ts := TimeSeries{ - Name: "Test", - XValues: []time.Time{ - time.Now().AddDate(0, 0, -5), - time.Now().AddDate(0, 0, -4), - time.Now().AddDate(0, 0, -3), - time.Now().AddDate(0, 0, -2), - time.Now().AddDate(0, 0, -1), - }, - YValues: []float64{ - 1.0, 2.0, 3.0, 4.0, 5.0, - }, - } - - x0, y0 := ts.GetValue(0) - assert.NotZero(x0) - assert.Equal(1.0, y0) -} diff --git a/style.go b/style.go index 9619aba..e4a2d5b 100644 --- a/style.go +++ b/style.go @@ -4,23 +4,28 @@ import ( "fmt" "strings" + "github.com/golang/freetype/truetype" "github.com/wcharczuk/go-chart/drawing" ) // Style is a simple style set. type Style struct { - Show bool - StrokeColor drawing.Color - FillColor drawing.Color + Show bool + Padding Box + StrokeWidth float64 - FontSize float64 - FontColor drawing.Color - Padding Box + StrokeColor drawing.Color + + FillColor drawing.Color + + FontSize float64 + FontColor drawing.Color + Font *truetype.Font } // IsZero returns if the object is set or not. func (s Style) IsZero() bool { - return s.StrokeColor.IsZero() && s.FillColor.IsZero() && s.StrokeWidth == 0 && s.FontSize == 0 + return s.StrokeColor.IsZero() && s.FillColor.IsZero() && s.StrokeWidth == 0 && s.FontSize == 0 && s.Font == nil } // GetStrokeColor returns the stroke color. @@ -78,6 +83,39 @@ func (s Style) GetFontColor(defaults ...drawing.Color) drawing.Color { return s.FontColor } +// GetFont returns the font face. +func (s Style) GetFont(defaults ...*truetype.Font) *truetype.Font { + if s.Font == nil { + if len(defaults) > 0 { + return defaults[0] + } + return nil + } + return s.Font +} + +// GetPadding returns the padding. +func (s Style) GetPadding(defaults ...Box) Box { + if s.Padding.IsZero() { + if len(defaults) > 0 { + return defaults[0] + } + return Box{} + } + return s.Padding +} + +// WithDefaultsFrom coalesces two styles into a new style. +func (s Style) WithDefaultsFrom(defaults Style) (final Style) { + final.FillColor = s.GetFillColor(defaults.FillColor) + final.FontColor = s.GetFontColor(defaults.FontColor) + final.Font = s.GetFont(defaults.Font) + final.Padding = s.GetPadding(defaults.Padding) + final.StrokeColor = s.GetStrokeColor(defaults.StrokeColor) + final.StrokeWidth = s.GetStrokeWidth(defaults.StrokeWidth) + return +} + // SVG returns the style as a svg style string. func (s Style) SVG(dpi float64) string { sw := s.StrokeWidth diff --git a/tick.go b/tick.go new file mode 100644 index 0000000..374a621 --- /dev/null +++ b/tick.go @@ -0,0 +1,25 @@ +package chart + +// Tick represents a label on an axis. +type Tick struct { + Value float64 + Label string +} + +// Ticks is an array of ticks. +type Ticks []Tick + +// Len returns the length of the ticks set. +func (t Ticks) Len() int { + return len(t) +} + +// Swap swaps two elements. +func (t Ticks) Swap(i, j int) { + t[i], t[j] = t[j], t[i] +} + +// Less returns if i's value is less than j's value. +func (t Ticks) Less(i, j int) bool { + return t[i].Value < t[j].Value +} diff --git a/time_series.go b/time_series.go index fd02b29..c61713e 100644 --- a/time_series.go +++ b/time_series.go @@ -1,17 +1,13 @@ package chart -import ( - "fmt" - "time" - - "github.com/blendlabs/go-util" -) +import "time" // TimeSeries is a line on a chart. type TimeSeries struct { - Name string - Style Style - FinalValueLabel Style + Name string + Style Style + + YAxis YAxisType XValues []time.Time YValues []float64 @@ -32,6 +28,11 @@ func (ts TimeSeries) Len() int { return len(ts.XValues) } +// GetYAxis returns which YAxis the series draws on. +func (ts TimeSeries) GetYAxis() YAxisType { + return ts.YAxis +} + // GetValue gets a value at a given index. func (ts TimeSeries) GetValue(index int) (x float64, y float64) { x = float64(ts.XValues[index].Unix()) @@ -39,28 +40,8 @@ func (ts TimeSeries) GetValue(index int) (x float64, y float64) { return } -// GetXFormatter returns the x value formatter. -func (ts TimeSeries) GetXFormatter() Formatter { - return func(v interface{}) string { - if typed, isTyped := v.(time.Time); isTyped { - return typed.Format(DefaultDateFormat) - } - if typed, isTyped := v.(int64); isTyped { - return time.Unix(typed, 0).Format(DefaultDateFormat) - } - if typed, isTyped := v.(float64); isTyped { - return time.Unix(int64(typed), 0).Format(DefaultDateFormat) - } - return util.StringEmpty - } -} - -// GetYFormatter returns the y value formatter. -func (ts TimeSeries) GetYFormatter() Formatter { - return func(v interface{}) string { - if typed, isTyped := v.(float64); isTyped { - return fmt.Sprintf("%0.2f", typed) - } - return util.StringEmpty - } +// Render renders the series. +func (ts TimeSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { + style := ts.Style.WithDefaultsFrom(defaults) + DrawLineSeries(r, canvasBox, xrange, yrange, style, ts) } diff --git a/util.go b/util.go index 85205dc..406bc3f 100644 --- a/util.go +++ b/util.go @@ -55,6 +55,10 @@ func Slices(count int, total float64) []float64 { return values } -func flf(v float64) string { - return fmt.Sprintf("%.2f", v) +// Float is an alias for float64 that provides a better .String() method. +type Float float64 + +// String returns the string representation of a float. +func (f Float) String() string { + return fmt.Sprintf("%.2f", f) } diff --git a/value_formatter.go b/value_formatter.go new file mode 100644 index 0000000..e02ba80 --- /dev/null +++ b/value_formatter.go @@ -0,0 +1,43 @@ +package chart + +import ( + "fmt" + "time" + + "github.com/blendlabs/go-util" +) + +// ValueFormatter is a function that takes a value and produces a string. +type ValueFormatter func(v interface{}) string + +// TimeValueFormatter is a ValueFormatter for timestamps. +func TimeValueFormatter(v interface{}) string { + return TimeValueFormatterWithFormat(v, DefaultDateFormat) +} + +// TimeValueFormatterWithFormat is a ValueFormatter for timestamps with a given format. +func TimeValueFormatterWithFormat(v interface{}, dateFormat string) string { + if typed, isTyped := v.(time.Time); isTyped { + return typed.Format(dateFormat) + } + if typed, isTyped := v.(int64); isTyped { + return time.Unix(typed, 0).Format(dateFormat) + } + if typed, isTyped := v.(float64); isTyped { + return time.Unix(int64(typed), 0).Format(dateFormat) + } + return util.StringEmpty +} + +// FloatValueFormatter is a ValueFormatter for float64. +func FloatValueFormatter(v interface{}) string { + return FloatValueFormatterWithFormat(v, "%.2f") +} + +// FloatValueFormatterWithFormat is a ValueFormatter for float64 with a given format. +func FloatValueFormatterWithFormat(v interface{}, floatFormat string) string { + if typed, isTyped := v.(float64); isTyped { + return fmt.Sprintf(floatFormat, typed) + } + return util.StringEmpty +} diff --git a/value_provider.go b/value_provider.go new file mode 100644 index 0000000..3119b7a --- /dev/null +++ b/value_provider.go @@ -0,0 +1,7 @@ +package chart + +// ValueProvider is a type that produces values. +type ValueProvider interface { + Len() int + GetValue(index int) (float64, float64) +} diff --git a/vector_renderer.go b/vector_renderer.go index 6e00796..9c06522 100644 --- a/vector_renderer.go +++ b/vector_renderer.go @@ -36,6 +36,11 @@ type vectorRenderer struct { fc *font.Drawer } +// GetDPI returns the dpi. +func (vr *vectorRenderer) GetDPI() float64 { + return vr.dpi +} + // SetDPI implements the interface method. func (vr *vectorRenderer) SetDPI(dpi float64) { vr.dpi = dpi diff --git a/xaxis.go b/xaxis.go new file mode 100644 index 0000000..243dc7c --- /dev/null +++ b/xaxis.go @@ -0,0 +1,27 @@ +package chart + +import "github.com/wcharczuk/go-chart/drawing" + +// XAxis represents the horizontal axis. +type XAxis struct { + axis +} + +// Render renders the axis +func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range) { + tickFontSize := xa.Style.GetFontSize(DefaultFontSize) + tickHeight := drawing.PointsToPixels(r.GetDPI(), tickFontSize) + ty := canvasBox.Bottom + DefaultXAxisMargin + int(tickHeight) + + r.SetFontColor(xa.Style.GetFontColor(DefaultAxisColor)) + r.SetFontSize(tickFontSize) + + ticks := xa.getTicks(ra) + + for _, t := range ticks { + v := t.Value + x := ra.Translate(v) + tx := canvasBox.Left + int(x) + r.Text(t.Label, tx, ty) + } +} diff --git a/yaxis.go b/yaxis.go new file mode 100644 index 0000000..752977c --- /dev/null +++ b/yaxis.go @@ -0,0 +1,28 @@ +package chart + +// YAxis is a veritcal rule of the range. +// There can be (2) y-axes; a primary and secondary. +type YAxis struct { + axis +} + +// Render renders the axis. +func (ya YAxis) Render(r Renderer, canvasBox Box, ra Range, axisType YAxisType) { + var tx int + if axisType == YAxisPrimary { + tx = canvasBox.Right + DefaultYAxisMargin + } else if axisType == YAxisSecondary { + tx = canvasBox.Left - DefaultYAxisMargin + } + + r.SetFontColor(ya.Style.GetFontColor(DefaultAxisColor)) + r.SetFontSize(ya.Style.GetFontSize(DefaultFontSize)) + + ticks := ya.getTicks(ra) + for _, t := range ticks { + v := t.Value + y := ra.Translate(v) + ty := int(y) + r.Text(t.Label, tx, ty) + } +} From abfdc3e0d988a064e1c89d5e8864005a0e664cc1 Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Sun, 10 Jul 2016 10:43:04 -0700 Subject: [PATCH 3/5] mostly works. --- annotation_series.go | 28 +++++- axis.go | 44 +-------- chart.go | 179 ++++++++++++++++++++++++++---------- continuous_series.go | 12 +++ defaults.go | 13 ++- drawing_helpers.go | 30 +++--- renderer.go | 2 +- series_test.go | 30 ++++++ testserver/main.go | 83 ++++++++++++----- time_series.go | 17 +++- value_formatter.go | 6 +- value_formatter_provider.go | 6 ++ xaxis.go | 86 +++++++++++++++-- yaxis.go | 88 ++++++++++++++++-- 14 files changed, 465 insertions(+), 159 deletions(-) create mode 100644 series_test.go create mode 100644 value_formatter_provider.go diff --git a/annotation_series.go b/annotation_series.go index a41aa58..678577c 100644 --- a/annotation_series.go +++ b/annotation_series.go @@ -14,13 +14,35 @@ type AnnotationSeries struct { Annotations []Annotation } +// GetName returns the name of the time series. +func (as AnnotationSeries) GetName() string { + return as.Name +} + +// GetStyle returns the line style. +func (as AnnotationSeries) GetStyle() Style { + return as.Style +} + +// GetYAxis returns which YAxis the series draws on. +func (as AnnotationSeries) GetYAxis() YAxisType { + return as.YAxis +} + // Render draws the series. -func (as AnnotationSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range) { +func (as AnnotationSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { if as.Style.Show { + style := as.Style.WithDefaultsFrom(Style{ + FillColor: DefaultAnnotationFillColor, + FontSize: DefaultAnnotationFontSize, + StrokeColor: defaults.StrokeColor, + StrokeWidth: defaults.StrokeWidth, + Padding: DefaultAnnotationPadding, + }) for _, a := range as.Annotations { - lx := xrange.Translate(a.X) + canvasBox.Left + lx := canvasBox.Right - xrange.Translate(a.X) ly := yrange.Translate(a.Y) + canvasBox.Top - DrawAnnotation(r, canvasBox, xrange, yrange, as.Style, lx, ly, a.Label) + DrawAnnotation(r, canvasBox, xrange, yrange, style, lx, ly, a.Label) } } } diff --git a/axis.go b/axis.go index 1ce0e7c..37586f1 100644 --- a/axis.go +++ b/axis.go @@ -14,46 +14,6 @@ const ( type Axis interface { GetName() string GetStyle() Style - Render(c *Chart, r Renderer, canvasBox Box, ra Range) -} - -// axis represents the basics of an axis implementation. -type axis struct { - Name string - Style Style - ValueFormatter ValueFormatter - Range Range - Ticks []Tick -} - -func (a axis) GetName() string { - return a.Name -} - -func (a axis) GetStyle() Style { - return a.Style -} - -func (a axis) getTicks(ra Range) []Tick { - if len(a.Ticks) > 0 { - return a.Ticks - } - return a.generateTicks(ra) -} - -func (a axis) generateTicks(ra Range) []Tick { - step := a.getTickStep(ra) - return a.generateTicksWithStep(ra, step) -} - -func (a axis) getTickCount(ra Range) int { - return 0 -} - -func (a axis) getTickStep(ra Range) float64 { - return 0.0 -} - -func (a axis) generateTicksWithStep(ra Range, step float64) []Tick { - return []Tick{} + GetTicks(r Renderer, ra Range, vf ValueFormatter) []Tick + Render(c *Chart, r Renderer, canvasBox Box, ra Range, ticks []Tick) } diff --git a/chart.go b/chart.go index 261d622..7153f1a 100644 --- a/chart.go +++ b/chart.go @@ -5,6 +5,7 @@ import ( "io" "github.com/golang/freetype/truetype" + "github.com/wcharczuk/go-chart/drawing" ) // Chart is what we're drawing. @@ -51,7 +52,7 @@ func (c Chart) GetFont() (*truetype.Font, error) { } // Render renders the chart with the given renderer to the given io.Writer. -func (c *Chart) Render(rp RendererProvider, w io.Writer) error { +func (c Chart) Render(rp RendererProvider, w io.Writer) error { if len(c.Series) == 0 { return errors.New("Please provide at least one series") } @@ -64,16 +65,26 @@ func (c *Chart) Render(rp RendererProvider, w io.Writer) error { if err != nil { return err } + c.Font = font r.SetFont(font) r.SetDPI(c.GetDPI(DefaultDPI)) xrange, yrange, yrangeAlt := c.getRanges() - canvasBox := c.getCanvasBox(r, xrange, yrange, yrangeAlt) - xrange, yrange, yrangeAlt = c.getRangeDomains(canvasBox, xrange, yrange, yrangeAlt) + canvasBox := c.getDefaultCanvasBox() + xf, yf, yfa := c.getValueFormatters() + + xrange, yrange, yrangeAlt = c.setRangeDomains(canvasBox, xrange, yrange, yrangeAlt) + xticks, yticks, yticksAlt := c.getAxesTicks(r, xrange, yrange, yrangeAlt, xf, yf, yfa) + canvasBox = c.getAdjustedCanvasBox(r, canvasBox, xticks, yticks, yticksAlt) + + // we do a second pass to take the updated domains into account + xrange, yrange, yrangeAlt = c.setRangeDomains(canvasBox, xrange, yrange, yrangeAlt) + xticks, yticks, yticksAlt = c.getAxesTicks(r, xrange, yrange, yrangeAlt, xf, yf, yfa) + canvasBox = c.getAdjustedCanvasBox(r, canvasBox, xticks, yticks, yticksAlt) c.drawBackground(r) c.drawCanvas(r, canvasBox) - c.drawAxes(r, canvasBox, xrange, yrange, yrangeAlt) + c.drawAxes(r, canvasBox, xrange, yrange, yrangeAlt, xticks, yticks, yticksAlt) for index, series := range c.Series { c.drawSeries(r, canvasBox, xrange, yrange, yrangeAlt, series, index) } @@ -147,21 +158,11 @@ func (c Chart) getRanges() (xrange, yrange, yrangeAlt Range) { return } -func (c Chart) getCanvasBox(r Renderer, xrange, yrange, yrangeAlt Range) Box { +func (c Chart) getDefaultCanvasBox() Box { dpl := c.Background.Padding.GetLeft(DefaultBackgroundPadding.Left) dpr := c.Background.Padding.GetRight(DefaultBackgroundPadding.Right) dpb := c.Background.Padding.GetBottom(DefaultBackgroundPadding.Bottom) - if c.YAxisSecondary.Style.Show { - dpl = c.getYAxisSecondaryWidth(r, yrangeAlt) - } - if c.YAxis.Style.Show { - dpr = c.getYAxisWidth(r, yrange) - } - if c.XAxis.Style.Show { - dpb = c.getXAxisHeight(r, xrange) - } - cb := Box{ Top: c.Background.Padding.GetTop(DefaultBackgroundPadding.Top), Left: dpl, @@ -173,23 +174,95 @@ func (c Chart) getCanvasBox(r Renderer, xrange, yrange, yrangeAlt Range) Box { return cb } -func (c Chart) getYAxisSecondaryWidth(r Renderer, ra Range) int { - var ll string - ticks := c.YAxisSecondary.getTicks(ra) - for _, t := range ticks { - if len(t.Label) > len(ll) { - ll = t.Label +func (c Chart) getValueFormatters() (x, y, ya ValueFormatter) { + for _, s := range c.Series { + if vfp, isVfp := s.(ValueFormatterProvider); isVfp { + sx, sy := vfp.GetValueFormatters() + if s.GetYAxis() == YAxisPrimary { + x = sx + y = sy + } else if s.GetYAxis() == YAxisSecondary { + x = sx + ya = sy + } } } - r.SetFontSize(c.YAxisSecondary.Style.GetFontSize(DefaultFontSize)) - r.SetFont(c.YAxisSecondary.Style.GetFont(c.Font)) - tw, _ := r.MeasureText(ll) - return tw + DefaultYAxisMargin + if c.XAxis.ValueFormatter != nil { + x = c.XAxis.ValueFormatter + } + if c.YAxis.ValueFormatter != nil { + y = c.YAxis.ValueFormatter + } + if c.YAxisSecondary.ValueFormatter != nil { + ya = c.YAxisSecondary.ValueFormatter + } + return } -func (c Chart) getYAxisWidth(r Renderer, ra Range) int { +func (c Chart) getAxesTicks(r Renderer, xr, yr, yar Range, xf, yf, yfa ValueFormatter) (xticks, yticks, yticksAlt []Tick) { + if c.XAxis.Style.Show { + xticks = c.XAxis.GetTicks(r, xr, xf) + } + if c.YAxis.Style.Show { + yticks = c.YAxis.GetTicks(r, yr, yf) + } + if c.YAxisSecondary.Style.Show { + yticksAlt = c.YAxisSecondary.GetTicks(r, yr, yf) + } + return +} + +func (c Chart) getAdjustedCanvasBox(r Renderer, defaults Box, xticks, yticks, yticksAlt []Tick) Box { + canvasBox := Box{} + + var dpl, dpr, dpb int + if c.XAxis.Style.Show { + dpb = c.getXAxisHeight(r, xticks) + } + if c.YAxis.Style.Show { + dpr = c.getYAxisWidth(r, yticks) + } + if c.YAxisSecondary.Style.Show { + dpl = c.getYAxisSecondaryWidth(r, yticksAlt) + } + + canvasBox.Top = defaults.Top + if dpl != 0 { + canvasBox.Left = c.Canvas.Padding.GetLeft(dpl) + } else { + canvasBox.Left = defaults.Left + } + if dpr != 0 { + canvasBox.Right = c.Width - c.Canvas.Padding.GetRight(dpr) + } else { + canvasBox.Right = defaults.Right + } + if dpb != 0 { + canvasBox.Bottom = c.Height - c.Canvas.Padding.GetBottom(dpb) + } else { + canvasBox.Bottom = defaults.Bottom + } + + canvasBox.Width = canvasBox.Right - canvasBox.Left + canvasBox.Height = canvasBox.Bottom - canvasBox.Top + return canvasBox +} + +func (c Chart) getXAxisHeight(r Renderer, ticks []Tick) int { + r.SetFontSize(c.XAxis.Style.GetFontSize(DefaultFontSize)) + r.SetFont(c.XAxis.Style.GetFont(c.Font)) + var tl int + for _, t := range ticks { + _, lh := r.MeasureText(t.Label) + if lh > tl { + tl = lh + } + } + return tl + DefaultXAxisMargin +} + +func (c Chart) getYAxisWidth(r Renderer, ticks []Tick) int { var ll string - ticks := c.YAxis.getTicks(ra) for _, t := range ticks { if len(t.Label) > len(ll) { ll = t.Label @@ -201,21 +274,21 @@ func (c Chart) getYAxisWidth(r Renderer, ra Range) int { return tw + DefaultYAxisMargin } -func (c Chart) getXAxisHeight(r Renderer, ra Range) int { - r.SetFontSize(c.XAxis.Style.GetFontSize(DefaultFontSize)) - r.SetFont(c.XAxis.Style.GetFont(c.Font)) - var tl int - ticks := c.YAxis.getTicks(ra) +func (c Chart) getYAxisSecondaryWidth(r Renderer, ticks []Tick) int { + var ll string for _, t := range ticks { - _, lh := r.MeasureText(t.Label) - if lh > tl { - tl = lh + if len(t.Label) > len(ll) { + ll = t.Label } } - return tl + DefaultXAxisMargin + + r.SetFontSize(c.YAxisSecondary.Style.GetFontSize(DefaultFontSize)) + r.SetFont(c.YAxisSecondary.Style.GetFont(c.Font)) + tw, _ := r.MeasureText(ll) + return tw + DefaultYAxisMargin } -func (c Chart) getRangeDomains(canvasBox Box, xrange, yrange, yrangeAlt Range) (Range, Range, Range) { +func (c Chart) setRangeDomains(canvasBox Box, xrange, yrange, yrangeAlt Range) (Range, Range, Range) { xrange.Domain = canvasBox.Width yrange.Domain = canvasBox.Height yrangeAlt.Domain = canvasBox.Height @@ -248,19 +321,19 @@ func (c Chart) drawCanvas(r Renderer, canvasBox Box) { r.FillStroke() } -func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range) { +func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range, xticks, yticks, yticksAlt []Tick) { if c.XAxis.Style.Show { - c.XAxis.Render(r, canvasBox, xrange) + c.XAxis.Render(r, canvasBox, xrange, xticks) } if c.YAxis.Style.Show { - c.YAxis.Render(r, canvasBox, yrange, YAxisPrimary) + c.YAxis.Render(r, canvasBox, yrange, YAxisPrimary, yticks) } if c.YAxisSecondary.Style.Show { - c.YAxisSecondary.Render(r, canvasBox, yrangeAlt, YAxisSecondary) + c.YAxisSecondary.Render(r, canvasBox, yrangeAlt, YAxisSecondary, yticksAlt) } } -func (c Chart) getSeriesDefaults(seriesIndex int) Style { +func (c Chart) getSeriesStyleDefaults(seriesIndex int) Style { strokeColor := GetDefaultSeriesStrokeColor(seriesIndex) return Style{ StrokeColor: strokeColor, @@ -273,21 +346,27 @@ func (c Chart) getSeriesDefaults(seriesIndex int) Style { func (c Chart) drawSeries(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range, s Series, seriesIndex int) { if s.GetYAxis() == YAxisPrimary { - s.Render(r, canvasBox, xrange, yrange, c.getSeriesDefaults(seriesIndex)) + s.Render(r, canvasBox, xrange, yrange, c.getSeriesStyleDefaults(seriesIndex)) } else if s.GetYAxis() == YAxisSecondary { - s.Render(r, canvasBox, xrange, yrange, c.getSeriesDefaults(seriesIndex)) + s.Render(r, canvasBox, xrange, yrange, c.getSeriesStyleDefaults(seriesIndex)) } } -func (c Chart) drawTitle(r Renderer) error { +func (c Chart) drawTitle(r Renderer) { if len(c.Title) > 0 && c.TitleStyle.Show { - r.SetFontColor(c.Canvas.GetFontColor(DefaultTextColor)) - titleFontSize := c.Canvas.GetFontSize(DefaultTitleFontSize) + r.SetFont(c.TitleStyle.GetFont(c.Font)) + r.SetFontColor(c.TitleStyle.GetFontColor(DefaultTextColor)) + titleFontSize := c.TitleStyle.GetFontSize(DefaultTitleFontSize) r.SetFontSize(titleFontSize) - textWidth, _ := r.MeasureText(c.Title) + + textWidthPoints, textHeightPoints := r.MeasureText(c.Title) + + textWidth := int(drawing.PointsToPixels(r.GetDPI(), float64(textWidthPoints))) + textHeight := int(drawing.PointsToPixels(r.GetDPI(), float64(textHeightPoints))) + titleX := (c.Width >> 1) - (textWidth >> 1) - titleY := c.TitleStyle.Padding.GetTop(DefaultTitleTop) + int(titleFontSize) + titleY := c.TitleStyle.Padding.GetTop(DefaultTitleTop) + textHeight + r.Text(c.Title, titleX, titleY) } - return nil } diff --git a/continuous_series.go b/continuous_series.go index b399727..57c145b 100644 --- a/continuous_series.go +++ b/continuous_series.go @@ -31,6 +31,18 @@ func (cs ContinuousSeries) GetValue(index int) (float64, float64) { return cs.XValues[index], cs.YValues[index] } +// GetValueFormatters returns value formatter defaults for the series. +func (cs ContinuousSeries) GetValueFormatters() (x, y ValueFormatter) { + x = FloatValueFormatter + y = FloatValueFormatter + return +} + +// GetYAxis returns which YAxis the series draws on. +func (cs ContinuousSeries) GetYAxis() YAxisType { + return cs.YAxis +} + // Render renders the series. func (cs ContinuousSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { style := cs.Style.WithDefaultsFrom(defaults) diff --git a/defaults.go b/defaults.go index b51df5e..f287438 100644 --- a/defaults.go +++ b/defaults.go @@ -32,18 +32,25 @@ const ( DefaultAxisFontSize = 10.0 // DefaultTitleTop is the default distance from the top of the chart to put the title. DefaultTitleTop = 10 + // DefaultYAxisMargin is the default distance from the right of the canvas to the y axis labels. - DefaultYAxisMargin = 5 + DefaultYAxisMargin = 10 // DefaultXAxisMargin is the default distance from bottom of the canvas to the x axis labels. DefaultXAxisMargin = 10 + + //DefaultVerticalTickWidth is half the margin. + DefaultVerticalTickWidth = DefaultYAxisMargin >> 1 + + //DefaultHorizontalTickWidth is half the margin. + DefaultHorizontalTickWidth = DefaultXAxisMargin >> 1 + // DefaultMinimumTickHorizontalSpacing is the minimum distance between horizontal ticks. DefaultMinimumTickHorizontalSpacing = 20 // DefaultMinimumTickVerticalSpacing is the minimum distance between vertical ticks. DefaultMinimumTickVerticalSpacing = 20 + // DefaultDateFormat is the default date format. DefaultDateFormat = "2006-01-02" - // DefaultMaxTickCount is the maximum number of ticks to draw - DefaultMaxTickCount = 7 ) var ( diff --git a/drawing_helpers.go b/drawing_helpers.go index 0fcff3d..03623d2 100644 --- a/drawing_helpers.go +++ b/drawing_helpers.go @@ -8,14 +8,13 @@ func DrawLineSeries(r Renderer, canvasBox Box, xrange, yrange Range, s Style, vs return } - cx := canvasBox.Left - cy := canvasBox.Top + ct := canvasBox.Top cb := canvasBox.Bottom - cw := canvasBox.Width + cr := canvasBox.Right v0x, v0y := vs.GetValue(0) - x0 := cw - xrange.Translate(v0x) - y0 := yrange.Translate(v0y) + x0 := cr - xrange.Translate(v0x) + y0 := yrange.Translate(v0y) + ct var vx, vy float64 var x, y int @@ -23,15 +22,15 @@ func DrawLineSeries(r Renderer, canvasBox Box, xrange, yrange Range, s Style, vs fill := s.GetFillColor() if !fill.IsZero() { r.SetFillColor(fill) - r.MoveTo(x0+cx, y0+cy) + r.MoveTo(x0, y0) for i := 1; i < vs.Len(); i++ { vx, vy = vs.GetValue(i) - x = cw - xrange.Translate(vx) - y = yrange.Translate(vy) - r.LineTo(x+cx, y+cy) + x = cr - xrange.Translate(vx) + y = yrange.Translate(vy) + ct + r.LineTo(x, y) } - r.LineTo(x+cx, cb) - r.LineTo(x0+cx, cb) + r.LineTo(x, cb) + r.LineTo(x0, cb) r.Close() r.Fill() } @@ -40,12 +39,12 @@ func DrawLineSeries(r Renderer, canvasBox Box, xrange, yrange Range, s Style, vs r.SetStrokeColor(stroke) r.SetStrokeWidth(s.GetStrokeWidth(DefaultStrokeWidth)) - r.MoveTo(x0+cx, y0+cy) + r.MoveTo(x0, y0) for i := 1; i < vs.Len(); i++ { vx, vy = vs.GetValue(i) - x = cw - xrange.Translate(vx) - y = yrange.Translate(vy) - r.LineTo(x+cx, y+cy) + x = cr - xrange.Translate(vx) + y = yrange.Translate(vy) + ct + r.LineTo(x, y) } r.Stroke() } @@ -81,6 +80,7 @@ func DrawAnnotation(r Renderer, canvasBox Box, xrange, yrange Range, s Style, lx r.SetFillColor(s.GetFillColor(DefaultAnnotationFillColor)) r.SetStrokeColor(s.GetStrokeColor()) r.SetStrokeWidth(s.GetStrokeWidth()) + r.MoveTo(lx, ly) r.LineTo(ltlx, ltly) r.LineTo(ltrx, ltry) diff --git a/renderer.go b/renderer.go index cf0c0f4..fa6d64a 100644 --- a/renderer.go +++ b/renderer.go @@ -9,7 +9,7 @@ import ( // Renderer represents the basic methods required to draw a chart. type Renderer interface { - // GetDPI returns the dpi for the renderer. + // GetDPI gets the DPI for the renderer. GetDPI() float64 // SetDPI sets the DPI for the renderer. diff --git a/series_test.go b/series_test.go new file mode 100644 index 0000000..3194997 --- /dev/null +++ b/series_test.go @@ -0,0 +1,30 @@ +package chart + +import ( + "testing" + "time" + + "github.com/blendlabs/go-assert" +) + +func TestTimeSeriesGetValue(t *testing.T) { + assert := assert.New(t) + + ts := TimeSeries{ + Name: "Test", + XValues: []time.Time{ + time.Now().AddDate(0, 0, -5), + time.Now().AddDate(0, 0, -4), + time.Now().AddDate(0, 0, -3), + time.Now().AddDate(0, 0, -2), + time.Now().AddDate(0, 0, -1), + }, + YValues: []float64{ + 1.0, 2.0, 3.0, 4.0, 5.0, + }, + } + + x0, y0 := ts.GetValue(0) + assert.NotZero(x0) + assert.Equal(1.0, y0) +} diff --git a/testserver/main.go b/testserver/main.go index 4e6db6a..6b6372a 100644 --- a/testserver/main.go +++ b/testserver/main.go @@ -5,7 +5,6 @@ import ( "net/http" "github.com/wcharczuk/go-chart" - "github.com/wcharczuk/go-chart/drawing" "github.com/wcharczuk/go-web" ) @@ -21,38 +20,73 @@ func chartHandler(rc *web.RequestContext) web.ControllerResult { rc.Response.Header().Set("Content-Type", "image/svg+xml") } + s1x := []float64{1.0, 2.0, 3.0, 4.0} + s1y := []float64{2.5, 5.0, 2.0, 3.3} + + s2x := []float64{3.0, 4.0, 5.0, 6.0} + s2y := []float64{6.0, 5.0, 4.0, 1.0} + c := chart.Chart{ Title: "A Test Chart", TitleStyle: chart.Style{ - Show: true, - FontSize: 26.0, - }, - Width: 640, - Height: 480, - Axes: chart.Style{ - Show: true, - StrokeWidth: 1.0, - }, - YRange: chart.Range{ - Min: 0.0, - Max: 7.0, - }, - FinalValueLabel: chart.Style{ Show: true, }, + Width: 1024, + Height: 400, + XAxis: chart.XAxis{ + Style: chart.Style{ + Show: true, + StrokeWidth: 1.0, + }, + }, + YAxis: chart.YAxis{ + Style: chart.Style{ + Show: true, + StrokeWidth: 1.0, + }, + Range: chart.Range{ + Min: 0.0, + Max: 7.0, + }, + }, Series: []chart.Series{ chart.ContinuousSeries{ Name: "a", - XValues: []float64{1.0, 2.0, 3.0, 4.0}, - YValues: []float64{2.5, 5.0, 2.0, 3.3}, - Style: chart.Style{ - FillColor: drawing.Color{R: 0, G: 116, B: 217, A: 128}, - }, + XValues: s1x, + YValues: s1y, }, chart.ContinuousSeries{ Name: "b", - XValues: []float64{3.0, 4.0, 5.0, 6.0}, - YValues: []float64{6.0, 5.0, 4.0, 1.0}, + XValues: s2x, + YValues: s2y, + }, + chart.AnnotationSeries{ + Name: "a - last value", + Style: chart.Style{ + Show: true, + StrokeColor: chart.GetDefaultSeriesStrokeColor(0), + }, + Annotations: []chart.Annotation{ + chart.Annotation{ + X: s1x[len(s1x)-1], + Y: s1y[len(s1y)-1], + Label: chart.FloatValueFormatter(s1y[len(s1y)-1]), + }, + }, + }, + chart.AnnotationSeries{ + Name: "b - last value", + Style: chart.Style{ + Show: true, + StrokeColor: chart.GetDefaultSeriesStrokeColor(1), + }, + Annotations: []chart.Annotation{ + chart.Annotation{ + X: s2x[len(s2x)-1], + Y: s2y[len(s2y)-1], + Label: chart.FloatValueFormatter(s2y[len(s2y)-1]), + }, + }, }, }, } @@ -74,6 +108,9 @@ func main() { app.SetName("Chart Test Server") app.SetLogger(web.NewStandardOutputLogger()) app.GET("/", chartHandler) - app.GET("/:format", chartHandler) + app.GET("/format/:format", chartHandler) + app.GET("/favico.ico", func(rc *web.RequestContext) web.ControllerResult { + return rc.Raw([]byte{}) + }) log.Fatal(app.Start()) } diff --git a/time_series.go b/time_series.go index c61713e..aec84d8 100644 --- a/time_series.go +++ b/time_series.go @@ -28,11 +28,6 @@ func (ts TimeSeries) Len() int { return len(ts.XValues) } -// GetYAxis returns which YAxis the series draws on. -func (ts TimeSeries) GetYAxis() YAxisType { - return ts.YAxis -} - // GetValue gets a value at a given index. func (ts TimeSeries) GetValue(index int) (x float64, y float64) { x = float64(ts.XValues[index].Unix()) @@ -40,6 +35,18 @@ func (ts TimeSeries) GetValue(index int) (x float64, y float64) { return } +// GetValueFormatters returns value formatter defaults for the series. +func (ts TimeSeries) GetValueFormatters() (x, y ValueFormatter) { + x = TimeValueFormatter + y = FloatValueFormatter + return +} + +// GetYAxis returns which YAxis the series draws on. +func (ts TimeSeries) GetYAxis() YAxisType { + return ts.YAxis +} + // Render renders the series. func (ts TimeSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { style := ts.Style.WithDefaultsFrom(defaults) diff --git a/value_formatter.go b/value_formatter.go index e02ba80..4a59974 100644 --- a/value_formatter.go +++ b/value_formatter.go @@ -3,8 +3,6 @@ package chart import ( "fmt" "time" - - "github.com/blendlabs/go-util" ) // ValueFormatter is a function that takes a value and produces a string. @@ -26,7 +24,7 @@ func TimeValueFormatterWithFormat(v interface{}, dateFormat string) string { if typed, isTyped := v.(float64); isTyped { return time.Unix(int64(typed), 0).Format(dateFormat) } - return util.StringEmpty + return "" } // FloatValueFormatter is a ValueFormatter for float64. @@ -39,5 +37,5 @@ func FloatValueFormatterWithFormat(v interface{}, floatFormat string) string { if typed, isTyped := v.(float64); isTyped { return fmt.Sprintf(floatFormat, typed) } - return util.StringEmpty + return "" } diff --git a/value_formatter_provider.go b/value_formatter_provider.go new file mode 100644 index 0000000..829fb1d --- /dev/null +++ b/value_formatter_provider.go @@ -0,0 +1,6 @@ +package chart + +// ValueFormatterProvider is a series that has custom formatters. +type ValueFormatterProvider interface { + GetValueFormatters() (x, y ValueFormatter) +} diff --git a/xaxis.go b/xaxis.go index 243dc7c..435b022 100644 --- a/xaxis.go +++ b/xaxis.go @@ -1,27 +1,101 @@ package chart -import "github.com/wcharczuk/go-chart/drawing" +import ( + "math" + "sort" + + "github.com/wcharczuk/go-chart/drawing" +) // XAxis represents the horizontal axis. type XAxis struct { - axis + Name string + Style Style + ValueFormatter ValueFormatter + Range Range + Ticks []Tick +} + +// GetName returns the name. +func (xa XAxis) GetName() string { + return xa.Name +} + +// GetStyle returns the style. +func (xa XAxis) GetStyle() Style { + return xa.Style +} + +// GetTicks returns the ticks for a series. It coalesces between user provided ticks and +// generated ticks. +func (xa XAxis) GetTicks(r Renderer, ra Range, vf ValueFormatter) []Tick { + if len(xa.Ticks) > 0 { + return xa.Ticks + } + return xa.generateTicks(r, ra, vf) +} + +func (xa XAxis) generateTicks(r Renderer, ra Range, vf ValueFormatter) []Tick { + step := xa.getTickStep(r, ra, vf) + return xa.generateTicksWithStep(ra, step, vf) +} + +func (xa XAxis) getTickCount(r Renderer, ra Range, vf ValueFormatter) int { + fontSize := xa.Style.GetFontSize(DefaultFontSize) + r.SetFontSize(fontSize) + + // take a cut at determining the 'widest' value. + l0 := vf(ra.Min) + ln := vf(ra.Max) + ll := l0 + if len(ln) > len(l0) { + ll = ln + } + llw, _ := r.MeasureText(ll) + textWidth := drawing.PointsToPixels(r.GetDPI(), float64(llw)) + width := textWidth + DefaultMinimumTickHorizontalSpacing + count := int(math.Ceil(float64(ra.Domain) / float64(width))) + return count +} + +func (xa XAxis) getTickStep(r Renderer, ra Range, vf ValueFormatter) float64 { + tickCount := xa.getTickCount(r, ra, vf) + step := ra.Delta() / float64(tickCount) + return step +} + +func (xa XAxis) generateTicksWithStep(ra Range, step float64, vf ValueFormatter) []Tick { + var ticks []Tick + for cursor := ra.Min; cursor < ra.Max; cursor += step { + ticks = append(ticks, Tick{ + Value: cursor, + Label: vf(cursor), + }) + } + return ticks } // Render renders the axis -func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range) { +func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range, ticks []Tick) { tickFontSize := xa.Style.GetFontSize(DefaultFontSize) tickHeight := drawing.PointsToPixels(r.GetDPI(), tickFontSize) ty := canvasBox.Bottom + DefaultXAxisMargin + int(tickHeight) + r.SetStrokeColor(xa.Style.GetStrokeColor(DefaultAxisColor)) + r.SetStrokeWidth(xa.Style.GetStrokeWidth(DefaultAxisLineWidth)) + + r.MoveTo(canvasBox.Left, canvasBox.Bottom) + r.LineTo(canvasBox.Right, canvasBox.Bottom) + r.Stroke() + r.SetFontColor(xa.Style.GetFontColor(DefaultAxisColor)) r.SetFontSize(tickFontSize) - ticks := xa.getTicks(ra) - + sort.Sort(Ticks(ticks)) for _, t := range ticks { v := t.Value x := ra.Translate(v) - tx := canvasBox.Left + int(x) + tx := canvasBox.Right - x r.Text(t.Label, tx, ty) } } diff --git a/yaxis.go b/yaxis.go index 752977c..df64406 100644 --- a/yaxis.go +++ b/yaxis.go @@ -1,28 +1,102 @@ package chart +import ( + "math" + "sort" +) + // YAxis is a veritcal rule of the range. // There can be (2) y-axes; a primary and secondary. type YAxis struct { - axis + Name string + Style Style + ValueFormatter ValueFormatter + Range Range + Ticks []Tick +} + +// GetName returns the name. +func (ya YAxis) GetName() string { + return ya.Name +} + +// GetStyle returns the style. +func (ya YAxis) GetStyle() Style { + return ya.Style +} + +// GetTicks returns the ticks for a series. It coalesces between user provided ticks and +// generated ticks. +func (ya YAxis) GetTicks(r Renderer, ra Range, vf ValueFormatter) []Tick { + if len(ya.Ticks) > 0 { + return ya.Ticks + } + return ya.generateTicks(r, ra, vf) +} + +func (ya YAxis) generateTicks(r Renderer, ra Range, vf ValueFormatter) []Tick { + step := ya.getTickStep(r, ra, vf) + return ya.generateTicksWithStep(ra, step, vf) +} + +func (ya YAxis) getTickCount(r Renderer, ra Range, vf ValueFormatter) int { + textHeight := int(ya.Style.GetFontSize(DefaultFontSize)) + height := textHeight + DefaultMinimumTickVerticalSpacing + count := int(math.Ceil(float64(ra.Domain) / float64(height))) + return count +} + +func (ya YAxis) getTickStep(r Renderer, ra Range, vf ValueFormatter) float64 { + tickCount := ya.getTickCount(r, ra, vf) + return ra.Delta() / float64(tickCount) +} + +func (ya YAxis) generateTicksWithStep(ra Range, step float64, vf ValueFormatter) []Tick { + var ticks []Tick + for cursor := ra.Min; cursor < ra.Max; cursor += step { + ticks = append(ticks, Tick{ + Value: cursor, + Label: vf(cursor), + }) + } + return ticks } // Render renders the axis. -func (ya YAxis) Render(r Renderer, canvasBox Box, ra Range, axisType YAxisType) { +func (ya YAxis) Render(r Renderer, canvasBox Box, ra Range, axisType YAxisType, ticks []Tick) { + var lx int var tx int if axisType == YAxisPrimary { + lx = canvasBox.Right tx = canvasBox.Right + DefaultYAxisMargin } else if axisType == YAxisSecondary { + lx = canvasBox.Left tx = canvasBox.Left - DefaultYAxisMargin } - r.SetFontColor(ya.Style.GetFontColor(DefaultAxisColor)) - r.SetFontSize(ya.Style.GetFontSize(DefaultFontSize)) + r.SetStrokeColor(ya.Style.GetStrokeColor(DefaultAxisColor)) + r.SetStrokeWidth(ya.Style.GetStrokeWidth(DefaultAxisLineWidth)) - ticks := ya.getTicks(ra) + r.MoveTo(lx, canvasBox.Bottom) + r.LineTo(lx, canvasBox.Top) + r.Stroke() + + r.SetFontColor(ya.Style.GetFontColor(DefaultAxisColor)) + fontSize := ya.Style.GetFontSize(DefaultFontSize) + r.SetFontSize(fontSize) + + sort.Sort(Ticks(ticks)) for _, t := range ticks { v := t.Value - y := ra.Translate(v) - ty := int(y) + ly := ra.Translate(v) + canvasBox.Top + + th := int(fontSize) >> 1 + ty := ly + th + r.Text(t.Label, tx, ty) + + r.MoveTo(lx, ly) + r.LineTo(lx+DefaultVerticalTickWidth, ly) + r.Stroke() } } From d78930a08f2f67a3c49cf70dc9372a0d1c9c6efc Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Sun, 10 Jul 2016 11:19:56 -0700 Subject: [PATCH 4/5] secondary axis works. --- chart.go | 12 ++++++-- testserver/main.go | 25 +++++++++++----- yaxis.go | 73 +++++++++++++++++++++++++++++++--------------- 3 files changed, 76 insertions(+), 34 deletions(-) diff --git a/chart.go b/chart.go index 7153f1a..47db2b6 100644 --- a/chart.go +++ b/chart.go @@ -155,6 +155,14 @@ func (c Chart) getRanges() (xrange, yrange, yrangeAlt Range) { yrange.Min = globalMinY yrange.Max = globalMaxY } + + if !c.YAxisSecondary.Range.IsZero() { + yrangeAlt.Min = c.YAxisSecondary.Range.Min + yrangeAlt.Max = c.YAxisSecondary.Range.Max + } else { + yrangeAlt.Min = globalMinYA + yrangeAlt.Max = globalMaxYA + } return } @@ -207,7 +215,7 @@ func (c Chart) getAxesTicks(r Renderer, xr, yr, yar Range, xf, yf, yfa ValueForm yticks = c.YAxis.GetTicks(r, yr, yf) } if c.YAxisSecondary.Style.Show { - yticksAlt = c.YAxisSecondary.GetTicks(r, yr, yf) + yticksAlt = c.YAxisSecondary.GetTicks(r, yar, yf) } return } @@ -348,7 +356,7 @@ func (c Chart) drawSeries(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt R if s.GetYAxis() == YAxisPrimary { s.Render(r, canvasBox, xrange, yrange, c.getSeriesStyleDefaults(seriesIndex)) } else if s.GetYAxis() == YAxisSecondary { - s.Render(r, canvasBox, xrange, yrange, c.getSeriesStyleDefaults(seriesIndex)) + s.Render(r, canvasBox, xrange, yrangeAlt, c.getSeriesStyleDefaults(seriesIndex)) } } diff --git a/testserver/main.go b/testserver/main.go index 6b6372a..0cee661 100644 --- a/testserver/main.go +++ b/testserver/main.go @@ -20,11 +20,11 @@ func chartHandler(rc *web.RequestContext) web.ControllerResult { rc.Response.Header().Set("Content-Type", "image/svg+xml") } - s1x := []float64{1.0, 2.0, 3.0, 4.0} + s1x := []float64{2.0, 3.0, 4.0, 5.0} s1y := []float64{2.5, 5.0, 2.0, 3.3} - s2x := []float64{3.0, 4.0, 5.0, 6.0} - s2y := []float64{6.0, 5.0, 4.0, 1.0} + s2x := []float64{0.0, 0.5, 1.0, 1.5} + s2y := []float64{1.1, 1.2, 1.0, 1.3} c := chart.Chart{ Title: "A Test Chart", @@ -35,20 +35,27 @@ func chartHandler(rc *web.RequestContext) web.ControllerResult { Height: 400, XAxis: chart.XAxis{ Style: chart.Style{ - Show: true, - StrokeWidth: 1.0, + Show: true, }, }, YAxis: chart.YAxis{ Style: chart.Style{ - Show: true, - StrokeWidth: 1.0, + Show: true, }, Range: chart.Range{ Min: 0.0, Max: 7.0, }, }, + YAxisSecondary: chart.YAxis{ + Style: chart.Style{ + Show: true, + }, + Range: chart.Range{ + Min: 0.8, + Max: 1.5, + }, + }, Series: []chart.Series{ chart.ContinuousSeries{ Name: "a", @@ -57,6 +64,7 @@ func chartHandler(rc *web.RequestContext) web.ControllerResult { }, chart.ContinuousSeries{ Name: "b", + YAxis: chart.YAxisSecondary, XValues: s2x, YValues: s2y, }, @@ -75,7 +83,8 @@ func chartHandler(rc *web.RequestContext) web.ControllerResult { }, }, chart.AnnotationSeries{ - Name: "b - last value", + Name: "b - last value", + YAxis: chart.YAxisSecondary, Style: chart.Style{ Show: true, StrokeColor: chart.GetDefaultSeriesStrokeColor(1), diff --git a/yaxis.go b/yaxis.go index df64406..f2d7a3c 100644 --- a/yaxis.go +++ b/yaxis.go @@ -1,6 +1,7 @@ package chart import ( + "fmt" "math" "sort" ) @@ -54,6 +55,7 @@ func (ya YAxis) getTickStep(r Renderer, ra Range, vf ValueFormatter) float64 { func (ya YAxis) generateTicksWithStep(ra Range, step float64, vf ValueFormatter) []Tick { var ticks []Tick for cursor := ra.Min; cursor < ra.Max; cursor += step { + println("yaxis tick:", fmt.Sprintf("%.2f", cursor)) ticks = append(ticks, Tick{ Value: cursor, Label: vf(cursor), @@ -64,39 +66,62 @@ func (ya YAxis) generateTicksWithStep(ra Range, step float64, vf ValueFormatter) // Render renders the axis. func (ya YAxis) Render(r Renderer, canvasBox Box, ra Range, axisType YAxisType, ticks []Tick) { - var lx int - var tx int - if axisType == YAxisPrimary { - lx = canvasBox.Right - tx = canvasBox.Right + DefaultYAxisMargin - } else if axisType == YAxisSecondary { - lx = canvasBox.Left - tx = canvasBox.Left - DefaultYAxisMargin - } - r.SetStrokeColor(ya.Style.GetStrokeColor(DefaultAxisColor)) r.SetStrokeWidth(ya.Style.GetStrokeWidth(DefaultAxisLineWidth)) - - r.MoveTo(lx, canvasBox.Bottom) - r.LineTo(lx, canvasBox.Top) - r.Stroke() - r.SetFontColor(ya.Style.GetFontColor(DefaultAxisColor)) fontSize := ya.Style.GetFontSize(DefaultFontSize) r.SetFontSize(fontSize) sort.Sort(Ticks(ticks)) - for _, t := range ticks { - v := t.Value - ly := ra.Translate(v) + canvasBox.Top - th := int(fontSize) >> 1 - ty := ly + th + var lx int + var tx int + if axisType == YAxisPrimary { + lx = canvasBox.Right + tx = canvasBox.Right + DefaultYAxisMargin - r.Text(t.Label, tx, ty) - - r.MoveTo(lx, ly) - r.LineTo(lx+DefaultVerticalTickWidth, ly) + r.MoveTo(lx, canvasBox.Bottom) + r.LineTo(lx, canvasBox.Top) r.Stroke() + + for _, t := range ticks { + v := t.Value + ly := ra.Translate(v) + canvasBox.Top + + th := int(fontSize) >> 1 + ty := ly + th + + r.Text(t.Label, tx, ty) + + r.MoveTo(lx, ly) + r.LineTo(lx+DefaultVerticalTickWidth, ly) + r.Stroke() + } + } else if axisType == YAxisSecondary { + lx = canvasBox.Left + + r.MoveTo(lx, canvasBox.Bottom) + r.LineTo(lx, canvasBox.Top) + r.Stroke() + + for _, t := range ticks { + v := t.Value + ly := ra.Translate(v) + canvasBox.Top + + ptw, _ := r.MeasureText(t.Label) + + tw := ptw + th := int(fontSize) + + tx = lx - (int(tw) + (DefaultYAxisMargin >> 1)) + ty := ly + th>>1 + + r.Text(t.Label, tx, ty) + + r.MoveTo(lx, ly) + r.LineTo(lx-DefaultVerticalTickWidth, ly) + r.Stroke() + } } + } From 1493409e95bd4dc9ce40d929cb52fd1609aa760f Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Sun, 10 Jul 2016 11:24:25 -0700 Subject: [PATCH 5/5] removing debugging message. --- yaxis.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/yaxis.go b/yaxis.go index f2d7a3c..e74325b 100644 --- a/yaxis.go +++ b/yaxis.go @@ -1,7 +1,6 @@ package chart import ( - "fmt" "math" "sort" ) @@ -55,7 +54,6 @@ func (ya YAxis) getTickStep(r Renderer, ra Range, vf ValueFormatter) float64 { func (ya YAxis) generateTicksWithStep(ra Range, step float64, vf ValueFormatter) []Tick { var ticks []Tick for cursor := ra.Min; cursor < ra.Max; cursor += step { - println("yaxis tick:", fmt.Sprintf("%.2f", cursor)) ticks = append(ticks, Tick{ Value: cursor, Label: vf(cursor),