Debian Codegraph @

chart.go

raw symbols SCIP
1 package chart
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "math"
8
9 "github.com/golang/freetype/truetype"
10 )
11
12 // Chart is what we're drawing.
13 type Chart struct {
14 Title string
15 TitleStyle Style
16
17 ColorPalette ColorPalette
18
19 Width int
20 Height int
21 DPI float64
22
23 Background Style
24 Canvas Style
25
26 XAxis XAxis
27 YAxis YAxis
28 YAxisSecondary YAxis
29
30 Font *truetype.Font
31 defaultFont *truetype.Font
32
33 Series []Series
34 Elements []Renderable
35
36 Log Logger
37 }
38
39 // GetDPI returns the dpi for the chart.
40 func (c Chart) GetDPI(defaults ...float64) float64 {
41 if c.DPI == 0 {
42 if len(defaults) > 0 {
43 return defaults[0]
44 }
45 return DefaultDPI
46 }
47 return c.DPI
48 }
49
50 // GetFont returns the text font.
51 func (c Chart) GetFont() *truetype.Font {
52 if c.Font == nil {
53 return c.defaultFont
54 }
55 return c.Font
56 }
57
58 // GetWidth returns the chart width or the default value.
59 func (c Chart) GetWidth() int {
60 if c.Width == 0 {
61 return DefaultChartWidth
62 }
63 return c.Width
64 }
65
66 // GetHeight returns the chart height or the default value.
67 func (c Chart) GetHeight() int {
68 if c.Height == 0 {
69 return DefaultChartHeight
70 }
71 return c.Height
72 }
73
74 // Render renders the chart with the given renderer to the given io.Writer.
75 func (c Chart) Render(rp RendererProvider, w io.Writer) error {
76 if len(c.Series) == 0 {
77 return errors.New("please provide at least one series")
78 }
79 if err := c.checkHasVisibleSeries(); err != nil {
80 return err
81 }
82
83 c.YAxisSecondary.AxisType = YAxisSecondary
84
85 r, err := rp(c.GetWidth(), c.GetHeight())
86 if err != nil {
87 return err
88 }
89
90 if c.Font == nil {
91 defaultFont, err := GetDefaultFont()
92 if err != nil {
93 return err
94 }
95 c.defaultFont = defaultFont
96 }
97 r.SetDPI(c.GetDPI(DefaultDPI))
98
99 c.drawBackground(r)
100
101 var xt, yt, yta []Tick
102 xr, yr, yra := c.getRanges()
103 canvasBox := c.getDefaultCanvasBox()
104 xf, yf, yfa := c.getValueFormatters()
105
106 Debugf(c.Log, "chart; canvas box: %v", canvasBox)
107
108 xr, yr, yra = c.setRangeDomains(canvasBox, xr, yr, yra)
109
110 err = c.checkRanges(xr, yr, yra)
111 if err != nil {
112 r.Save(w)
113 return err
114 }
115
116 if c.hasAxes() {
117 xt, yt, yta = c.getAxesTicks(r, xr, yr, yra, xf, yf, yfa)
118 canvasBox = c.getAxesAdjustedCanvasBox(r, canvasBox, xr, yr, yra, xt, yt, yta)
119 xr, yr, yra = c.setRangeDomains(canvasBox, xr, yr, yra)
120
121 Debugf(c.Log, "chart; axes adjusted canvas box: %v", canvasBox)
122
123 // do a second pass in case things haven't settled yet.
124 xt, yt, yta = c.getAxesTicks(r, xr, yr, yra, xf, yf, yfa)
125 canvasBox = c.getAxesAdjustedCanvasBox(r, canvasBox, xr, yr, yra, xt, yt, yta)
126 xr, yr, yra = c.setRangeDomains(canvasBox, xr, yr, yra)
127 }
128
129 if c.hasAnnotationSeries() {
130 canvasBox = c.getAnnotationAdjustedCanvasBox(r, canvasBox, xr, yr, yra, xf, yf, yfa)
131 xr, yr, yra = c.setRangeDomains(canvasBox, xr, yr, yra)
132 xt, yt, yta = c.getAxesTicks(r, xr, yr, yra, xf, yf, yfa)
133
134 Debugf(c.Log, "chart; annotation adjusted canvas box: %v", canvasBox)
135 }
136
137 c.drawCanvas(r, canvasBox)
138 c.drawAxes(r, canvasBox, xr, yr, yra, xt, yt, yta)
139 for index, series := range c.Series {
140 c.drawSeries(r, canvasBox, xr, yr, yra, series, index)
141 }
142
143 c.drawTitle(r)
144
145 for _, a := range c.Elements {
146 a(r, canvasBox, c.styleDefaultsElements())
147 }
148
149 return r.Save(w)
150 }
151
152 func (c Chart) checkHasVisibleSeries() error {
153 var style Style
154 for _, s := range c.Series {
155 style = s.GetStyle()
156 if !style.Hidden {
157 return nil
158 }
159 }
160 return fmt.Errorf("chart render; must have (1) visible series")
161 }
162
163 func (c Chart) validateSeries() error {
164 var err error
165 for _, s := range c.Series {
166 err = s.Validate()
167 if err != nil {
168 return err
169 }
170 }
171 return nil
172 }
173
174 func (c Chart) getRanges() (xrange, yrange, yrangeAlt Range) {
175 var minx, maxx float64 = math.MaxFloat64, -math.MaxFloat64
176 var miny, maxy float64 = math.MaxFloat64, -math.MaxFloat64
177 var minya, maxya float64 = math.MaxFloat64, -math.MaxFloat64
178
179 seriesMappedToSecondaryAxis := false
180
181 // note: a possible future optimization is to not scan the series values if
182 // all axis are represented by either custom ticks or custom ranges.
183 for _, s := range c.Series {
184 if !s.GetStyle().Hidden {
185 seriesAxis := s.GetYAxis()
186 if bvp, isBoundedValuesProvider := s.(BoundedValuesProvider); isBoundedValuesProvider {
187 seriesLength := bvp.Len()
188 for index := 0; index < seriesLength; index++ {
189 vx, vy1, vy2 := bvp.GetBoundedValues(index)
190
191 minx = math.Min(minx, vx)
192 maxx = math.Max(maxx, vx)
193
194 if seriesAxis == YAxisPrimary {
195 miny = math.Min(miny, vy1)
196 miny = math.Min(miny, vy2)
197 maxy = math.Max(maxy, vy1)
198 maxy = math.Max(maxy, vy2)
199 } else if seriesAxis == YAxisSecondary {
200 minya = math.Min(minya, vy1)
201 minya = math.Min(minya, vy2)
202 maxya = math.Max(maxya, vy1)
203 maxya = math.Max(maxya, vy2)
204 seriesMappedToSecondaryAxis = true
205 }
206 }
207 } else if vp, isValuesProvider := s.(ValuesProvider); isValuesProvider {
208 seriesLength := vp.Len()
209 for index := 0; index < seriesLength; index++ {
210 vx, vy := vp.GetValues(index)
211
212 minx = math.Min(minx, vx)
213 maxx = math.Max(maxx, vx)
214
215 if seriesAxis == YAxisPrimary {
216 miny = math.Min(miny, vy)
217 maxy = math.Max(maxy, vy)
218 } else if seriesAxis == YAxisSecondary {
219 minya = math.Min(minya, vy)
220 maxya = math.Max(maxya, vy)
221 seriesMappedToSecondaryAxis = true
222 }
223 }
224 }
225 }
226 }
227
228 if c.XAxis.Range == nil {
229 xrange = &ContinuousRange{}
230 } else {
231 xrange = c.XAxis.Range
232 }
233
234 if c.YAxis.Range == nil {
235 yrange = &ContinuousRange{}
236 } else {
237 yrange = c.YAxis.Range
238 }
239
240 if c.YAxisSecondary.Range == nil {
241 yrangeAlt = &ContinuousRange{}
242 } else {
243 yrangeAlt = c.YAxisSecondary.Range
244 }
245
246 if len(c.XAxis.Ticks) > 0 {
247 tickMin, tickMax := math.MaxFloat64, -math.MaxFloat64
248 for _, t := range c.XAxis.Ticks {
249 tickMin = math.Min(tickMin, t.Value)
250 tickMax = math.Max(tickMax, t.Value)
251 }
252 xrange.SetMin(tickMin)
253 xrange.SetMax(tickMax)
254 } else if xrange.IsZero() {
255 xrange.SetMin(minx)
256 xrange.SetMax(maxx)
257 }
258
259 if len(c.YAxis.Ticks) > 0 {
260 tickMin, tickMax := math.MaxFloat64, -math.MaxFloat64
261 for _, t := range c.YAxis.Ticks {
262 tickMin = math.Min(tickMin, t.Value)
263 tickMax = math.Max(tickMax, t.Value)
264 }
265 yrange.SetMin(tickMin)
266 yrange.SetMax(tickMax)
267 } else if yrange.IsZero() {
268 yrange.SetMin(miny)
269 yrange.SetMax(maxy)
270
271 if !c.YAxis.Style.Hidden {
272 delta := yrange.GetDelta()
273 roundTo := GetRoundToForDelta(delta)
274 rmin, rmax := RoundDown(yrange.GetMin(), roundTo), RoundUp(yrange.GetMax(), roundTo)
275
276 yrange.SetMin(rmin)
277 yrange.SetMax(rmax)
278 }
279 }
280
281 if len(c.YAxisSecondary.Ticks) > 0 {
282 tickMin, tickMax := math.MaxFloat64, -math.MaxFloat64
283 for _, t := range c.YAxis.Ticks {
284 tickMin = math.Min(tickMin, t.Value)
285 tickMax = math.Max(tickMax, t.Value)
286 }
287 yrangeAlt.SetMin(tickMin)
288 yrangeAlt.SetMax(tickMax)
289 } else if seriesMappedToSecondaryAxis && yrangeAlt.IsZero() {
290 yrangeAlt.SetMin(minya)
291 yrangeAlt.SetMax(maxya)
292
293 if !c.YAxisSecondary.Style.Hidden {
294 delta := yrangeAlt.GetDelta()
295 roundTo := GetRoundToForDelta(delta)
296 rmin, rmax := RoundDown(yrangeAlt.GetMin(), roundTo), RoundUp(yrangeAlt.GetMax(), roundTo)
297 yrangeAlt.SetMin(rmin)
298 yrangeAlt.SetMax(rmax)
299 }
300 }
301
302 return
303 }
304
305 func (c Chart) checkRanges(xr, yr, yra Range) error {
306 Debugf(c.Log, "checking xrange: %v", xr)
307 xDelta := xr.GetDelta()
308 if math.IsInf(xDelta, 0) {
309 return errors.New("infinite x-range delta")
310 }
311 if math.IsNaN(xDelta) {
312 return errors.New("nan x-range delta")
313 }
314 if xDelta == 0 {
315 return errors.New("zero x-range delta; there needs to be at least (2) values")
316 }
317
318 Debugf(c.Log, "checking yrange: %v", yr)
319 yDelta := yr.GetDelta()
320 if math.IsInf(yDelta, 0) {
321 return errors.New("infinite y-range delta")
322 }
323 if math.IsNaN(yDelta) {
324 return errors.New("nan y-range delta")
325 }
326
327 if c.hasSecondarySeries() {
328 Debugf(c.Log, "checking secondary yrange: %v", yra)
329 yraDelta := yra.GetDelta()
330 if math.IsInf(yraDelta, 0) {
331 return errors.New("infinite secondary y-range delta")
332 }
333 if math.IsNaN(yraDelta) {
334 return errors.New("nan secondary y-range delta")
335 }
336 }
337
338 return nil
339 }
340
341 func (c Chart) getDefaultCanvasBox() Box {
342 return c.Box()
343 }
344
345 func (c Chart) getValueFormatters() (x, y, ya ValueFormatter) {
346 for _, s := range c.Series {
347 if vfp, isVfp := s.(ValueFormatterProvider); isVfp {
348 sx, sy := vfp.GetValueFormatters()
349 if s.GetYAxis() == YAxisPrimary {
350 x = sx
351 y = sy
352 } else if s.GetYAxis() == YAxisSecondary {
353 x = sx
354 ya = sy
355 }
356 }
357 }
358 if c.XAxis.ValueFormatter != nil {
359 x = c.XAxis.GetValueFormatter()
360 }
361 if c.YAxis.ValueFormatter != nil {
362 y = c.YAxis.GetValueFormatter()
363 }
364 if c.YAxisSecondary.ValueFormatter != nil {
365 ya = c.YAxisSecondary.GetValueFormatter()
366 }
367 return
368 }
369
370 func (c Chart) hasAxes() bool {
371 return !c.XAxis.Style.Hidden || !c.YAxis.Style.Hidden || !c.YAxisSecondary.Style.Hidden
372 }
373
374 func (c Chart) getAxesTicks(r Renderer, xr, yr, yar Range, xf, yf, yfa ValueFormatter) (xticks, yticks, yticksAlt []Tick) {
375 if !c.XAxis.Style.Hidden {
376 xticks = c.XAxis.GetTicks(r, xr, c.styleDefaultsAxes(), xf)
377 }
378 if !c.YAxis.Style.Hidden {
379 yticks = c.YAxis.GetTicks(r, yr, c.styleDefaultsAxes(), yf)
380 }
381 if !c.YAxisSecondary.Style.Hidden {
382 yticksAlt = c.YAxisSecondary.GetTicks(r, yar, c.styleDefaultsAxes(), yfa)
383 }
384 return
385 }
386
387 func (c Chart) getAxesAdjustedCanvasBox(r Renderer, canvasBox Box, xr, yr, yra Range, xticks, yticks, yticksAlt []Tick) Box {
388 axesOuterBox := canvasBox.Clone()
389 if !c.XAxis.Style.Hidden {
390 axesBounds := c.XAxis.Measure(r, canvasBox, xr, c.styleDefaultsAxes(), xticks)
391 Debugf(c.Log, "chart; x-axis measured %v", axesBounds)
392 axesOuterBox = axesOuterBox.Grow(axesBounds)
393 }
394 if !c.YAxis.Style.Hidden {
395 axesBounds := c.YAxis.Measure(r, canvasBox, yr, c.styleDefaultsAxes(), yticks)
396 Debugf(c.Log, "chart; y-axis measured %v", axesBounds)
397 axesOuterBox = axesOuterBox.Grow(axesBounds)
398 }
399 if !c.YAxisSecondary.Style.Hidden && c.hasSecondarySeries() {
400 axesBounds := c.YAxisSecondary.Measure(r, canvasBox, yra, c.styleDefaultsAxes(), yticksAlt)
401 Debugf(c.Log, "chart; y-axis secondary measured %v", axesBounds)
402 axesOuterBox = axesOuterBox.Grow(axesBounds)
403 }
404
405 return canvasBox.OuterConstrain(c.Box(), axesOuterBox)
406 }
407
408 func (c Chart) setRangeDomains(canvasBox Box, xr, yr, yra Range) (Range, Range, Range) {
409 xr.SetDomain(canvasBox.Width())
410 yr.SetDomain(canvasBox.Height())
411 yra.SetDomain(canvasBox.Height())
412 return xr, yr, yra
413 }
414
415 func (c Chart) hasAnnotationSeries() bool {
416 for _, s := range c.Series {
417 if as, isAnnotationSeries := s.(AnnotationSeries); isAnnotationSeries {
418 if !as.GetStyle().Hidden {
419 return true
420 }
421 }
422 }
423 return false
424 }
425
426 func (c Chart) hasSecondarySeries() bool {
427 for _, s := range c.Series {
428 if s.GetYAxis() == YAxisSecondary {
429 return true
430 }
431 }
432 return false
433 }
434
435 func (c Chart) getAnnotationAdjustedCanvasBox(r Renderer, canvasBox Box, xr, yr, yra Range, xf, yf, yfa ValueFormatter) Box {
436 annotationSeriesBox := canvasBox.Clone()
437 for seriesIndex, s := range c.Series {
438 if as, isAnnotationSeries := s.(AnnotationSeries); isAnnotationSeries {
439 if !as.GetStyle().Hidden {
440 style := c.styleDefaultsSeries(seriesIndex)
441 var annotationBounds Box
442 if as.YAxis == YAxisPrimary {
443 annotationBounds = as.Measure(r, canvasBox, xr, yr, style)
444 } else if as.YAxis == YAxisSecondary {
445 annotationBounds = as.Measure(r, canvasBox, xr, yra, style)
446 }
447
448 annotationSeriesBox = annotationSeriesBox.Grow(annotationBounds)
449 }
450 }
451 }
452
453 return canvasBox.OuterConstrain(c.Box(), annotationSeriesBox)
454 }
455
456 func (c Chart) getBackgroundStyle() Style {
457 return c.Background.InheritFrom(c.styleDefaultsBackground())
458 }
459
460 func (c Chart) drawBackground(r Renderer) {
461 Draw.Box(r, Box{
462 Right: c.GetWidth(),
463 Bottom: c.GetHeight(),
464 }, c.getBackgroundStyle())
465 }
466
467 func (c Chart) getCanvasStyle() Style {
468 return c.Canvas.InheritFrom(c.styleDefaultsCanvas())
469 }
470
471 func (c Chart) drawCanvas(r Renderer, canvasBox Box) {
472 Draw.Box(r, canvasBox, c.getCanvasStyle())
473 }
474
475 func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range, xticks, yticks, yticksAlt []Tick) {
476 if !c.XAxis.Style.Hidden {
477 c.XAxis.Render(r, canvasBox, xrange, c.styleDefaultsAxes(), xticks)
478 }
479 if !c.YAxis.Style.Hidden {
480 c.YAxis.Render(r, canvasBox, yrange, c.styleDefaultsAxes(), yticks)
481 }
482 if !c.YAxisSecondary.Style.Hidden {
483 c.YAxisSecondary.Render(r, canvasBox, yrangeAlt, c.styleDefaultsAxes(), yticksAlt)
484 }
485 }
486
487 func (c Chart) drawSeries(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range, s Series, seriesIndex int) {
488 if !s.GetStyle().Hidden {
489 if s.GetYAxis() == YAxisPrimary {
490 s.Render(r, canvasBox, xrange, yrange, c.styleDefaultsSeries(seriesIndex))
491 } else if s.GetYAxis() == YAxisSecondary {
492 s.Render(r, canvasBox, xrange, yrangeAlt, c.styleDefaultsSeries(seriesIndex))
493 }
494 }
495 }
496
497 func (c Chart) drawTitle(r Renderer) {
498 if len(c.Title) > 0 && !c.TitleStyle.Hidden {
499 r.SetFont(c.TitleStyle.GetFont(c.GetFont()))
500 r.SetFontColor(c.TitleStyle.GetFontColor(c.GetColorPalette().TextColor()))
501 titleFontSize := c.TitleStyle.GetFontSize(DefaultTitleFontSize)
502 r.SetFontSize(titleFontSize)
503
504 textBox := r.MeasureText(c.Title)
505
506 textWidth := textBox.Width()
507 textHeight := textBox.Height()
508
509 titleX := (c.GetWidth() >> 1) - (textWidth >> 1)
510 titleY := c.TitleStyle.Padding.GetTop(DefaultTitleTop) + textHeight
511
512 r.Text(c.Title, titleX, titleY)
513 }
514 }
515
516 func (c Chart) styleDefaultsBackground() Style {
517 return Style{
518 FillColor: c.GetColorPalette().BackgroundColor(),
519 StrokeColor: c.GetColorPalette().BackgroundStrokeColor(),
520 StrokeWidth: DefaultBackgroundStrokeWidth,
521 }
522 }
523
524 func (c Chart) styleDefaultsCanvas() Style {
525 return Style{
526 FillColor: c.GetColorPalette().CanvasColor(),
527 StrokeColor: c.GetColorPalette().CanvasStrokeColor(),
528 StrokeWidth: DefaultCanvasStrokeWidth,
529 }
530 }
531
532 func (c Chart) styleDefaultsSeries(seriesIndex int) Style {
533 return Style{
534 DotColor: c.GetColorPalette().GetSeriesColor(seriesIndex),
535 StrokeColor: c.GetColorPalette().GetSeriesColor(seriesIndex),
536 StrokeWidth: DefaultSeriesLineWidth,
537 Font: c.GetFont(),
538 FontSize: DefaultFontSize,
539 }
540 }
541
542 func (c Chart) styleDefaultsAxes() Style {
543 return Style{
544 Font: c.GetFont(),
545 FontColor: c.GetColorPalette().TextColor(),
546 FontSize: DefaultAxisFontSize,
547 StrokeColor: c.GetColorPalette().AxisStrokeColor(),
548 StrokeWidth: DefaultAxisLineWidth,
549 }
550 }
551
552 func (c Chart) styleDefaultsElements() Style {
553 return Style{
554 Font: c.GetFont(),
555 }
556 }
557
558 // GetColorPalette returns the color palette for the chart.
559 func (c Chart) GetColorPalette() ColorPalette {
560 if c.ColorPalette != nil {
561 return c.ColorPalette
562 }
563 return DefaultColorPalette
564 }
565
566 // Box returns the chart bounds as a box.
567 func (c Chart) Box() Box {
568 dpr := c.Background.Padding.GetRight(DefaultBackgroundPadding.Right)
569 dpb := c.Background.Padding.GetBottom(DefaultBackgroundPadding.Bottom)
570
571 return Box{
572 Top: c.Background.Padding.GetTop(DefaultBackgroundPadding.Top),
573 Left: c.Background.Padding.GetLeft(DefaultBackgroundPadding.Left),
574 Right: c.GetWidth() - dpr,
575 Bottom: c.GetHeight() - dpb,
576 }
577 }