Debian Codegraph @

stacked_bar_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 // StackedBar is a bar within a StackedBarChart.
13 type StackedBar struct {
14 Name string
15 Width int
16 Values []Value
17 }
18
19 // GetWidth returns the width of the bar.
20 func (sb StackedBar) GetWidth() int {
21 if sb.Width == 0 {
22 return 50
23 }
24 return sb.Width
25 }
26
27 // StackedBarChart is a chart that draws sections of a bar based on percentages.
28 type StackedBarChart struct {
29 Title string
30 TitleStyle Style
31
32 ColorPalette ColorPalette
33
34 Width int
35 Height int
36 DPI float64
37
38 Background Style
39 Canvas Style
40
41 XAxis Style
42 YAxis Style
43
44 BarSpacing int
45
46 Font *truetype.Font
47 defaultFont *truetype.Font
48
49 IsHorizontal bool
50
51 Bars []StackedBar
52 Elements []Renderable
53 }
54
55 // GetDPI returns the dpi for the chart.
56 func (sbc StackedBarChart) GetDPI(defaults ...float64) float64 {
57 if sbc.DPI == 0 {
58 if len(defaults) > 0 {
59 return defaults[0]
60 }
61 return DefaultDPI
62 }
63 return sbc.DPI
64 }
65
66 // GetFont returns the text font.
67 func (sbc StackedBarChart) GetFont() *truetype.Font {
68 if sbc.Font == nil {
69 return sbc.defaultFont
70 }
71 return sbc.Font
72 }
73
74 // GetWidth returns the chart width or the default value.
75 func (sbc StackedBarChart) GetWidth() int {
76 if sbc.Width == 0 {
77 return DefaultChartWidth
78 }
79 return sbc.Width
80 }
81
82 // GetHeight returns the chart height or the default value.
83 func (sbc StackedBarChart) GetHeight() int {
84 if sbc.Height == 0 {
85 return DefaultChartWidth
86 }
87 return sbc.Height
88 }
89
90 // GetBarSpacing returns the spacing between bars.
91 func (sbc StackedBarChart) GetBarSpacing() int {
92 if sbc.BarSpacing == 0 {
93 return 100
94 }
95 return sbc.BarSpacing
96 }
97
98 // Render renders the chart with the given renderer to the given io.Writer.
99 func (sbc StackedBarChart) Render(rp RendererProvider, w io.Writer) error {
100 if len(sbc.Bars) == 0 {
101 return errors.New("please provide at least one bar")
102 }
103
104 r, err := rp(sbc.GetWidth(), sbc.GetHeight())
105 if err != nil {
106 return err
107 }
108
109 if sbc.Font == nil {
110 defaultFont, err := GetDefaultFont()
111 if err != nil {
112 return err
113 }
114 sbc.defaultFont = defaultFont
115 }
116 r.SetDPI(sbc.GetDPI(DefaultDPI))
117
118 var canvasBox Box
119 if sbc.IsHorizontal {
120 canvasBox = sbc.getHorizontalAdjustedCanvasBox(r, sbc.getDefaultCanvasBox())
121 if err := canvasBox.Validate(); err != nil {
122 return fmt.Errorf("invalid canvas box: %w", err)
123 }
124 sbc.drawCanvas(r, canvasBox)
125 sbc.drawHorizontalBars(r, canvasBox)
126 sbc.drawHorizontalXAxis(r, canvasBox)
127 sbc.drawHorizontalYAxis(r, canvasBox)
128 } else {
129 canvasBox = sbc.getAdjustedCanvasBox(r, sbc.getDefaultCanvasBox())
130 if err := canvasBox.Validate(); err != nil {
131 return fmt.Errorf("invalid canvas box: %w", err)
132 }
133 sbc.drawCanvas(r, canvasBox)
134 sbc.drawBars(r, canvasBox)
135 sbc.drawXAxis(r, canvasBox)
136 sbc.drawYAxis(r, canvasBox)
137 }
138
139 sbc.drawTitle(r)
140 for _, a := range sbc.Elements {
141 a(r, canvasBox, sbc.styleDefaultsElements())
142 }
143
144 return r.Save(w)
145 }
146
147 func (sbc StackedBarChart) drawCanvas(r Renderer, canvasBox Box) {
148 Draw.Box(r, canvasBox, sbc.getCanvasStyle())
149 }
150
151 func (sbc StackedBarChart) drawBars(r Renderer, canvasBox Box) {
152 xoffset := canvasBox.Left
153 for _, bar := range sbc.Bars {
154 sbc.drawBar(r, canvasBox, xoffset, bar)
155 xoffset += (sbc.GetBarSpacing() + bar.GetWidth())
156 }
157 }
158
159 func (sbc StackedBarChart) drawHorizontalBars(r Renderer, canvasBox Box) {
160 yOffset := canvasBox.Top
161 for _, bar := range sbc.Bars {
162 sbc.drawHorizontalBar(r, canvasBox, yOffset, bar)
163 yOffset += sbc.GetBarSpacing() + bar.GetWidth()
164 }
165 }
166
167 func (sbc StackedBarChart) drawBar(r Renderer, canvasBox Box, xoffset int, bar StackedBar) int {
168 barSpacing2 := sbc.GetBarSpacing() >> 1
169 bxl := xoffset + barSpacing2
170 bxr := bxl + bar.GetWidth()
171
172 normalizedBarComponents := Values(bar.Values).Normalize()
173 yoffset := canvasBox.Top
174 for index, bv := range normalizedBarComponents {
175 barHeight := int(math.Ceil(bv.Value * float64(canvasBox.Height())))
176 barBox := Box{
177 Top: yoffset,
178 Left: bxl,
179 Right: bxr,
180 Bottom: MinInt(yoffset+barHeight, canvasBox.Bottom-DefaultStrokeWidth),
181 }
182 Draw.Box(r, barBox, bv.Style.InheritFrom(sbc.styleDefaultsStackedBarValue(index)))
183 yoffset += barHeight
184 }
185
186 // draw the labels
187 yoffset = canvasBox.Top
188 var lx, ly int
189 for index, bv := range normalizedBarComponents {
190 barHeight := int(math.Ceil(bv.Value * float64(canvasBox.Height())))
191
192 if len(bv.Label) > 0 {
193 lx = bxl + ((bxr - bxl) / 2)
194 ly = yoffset + (barHeight / 2)
195
196 bv.Style.InheritFrom(sbc.styleDefaultsStackedBarValue(index)).WriteToRenderer(r)
197 tb := r.MeasureText(bv.Label)
198 lx = lx - (tb.Width() >> 1)
199 ly = ly + (tb.Height() >> 1)
200
201 if lx < 0 {
202 lx = 0
203 }
204 if ly < 0 {
205 lx = 0
206 }
207
208 r.Text(bv.Label, lx, ly)
209 }
210 yoffset += barHeight
211 }
212
213 return bxr
214 }
215
216 func (sbc StackedBarChart) drawHorizontalBar(r Renderer, canvasBox Box, yoffset int, bar StackedBar) {
217 halfBarSpacing := sbc.GetBarSpacing() >> 1
218
219 boxTop := yoffset + halfBarSpacing
220 boxBottom := boxTop + bar.GetWidth()
221
222 normalizedBarComponents := Values(bar.Values).Normalize()
223
224 xOffset := canvasBox.Right
225 for index, bv := range normalizedBarComponents {
226 barHeight := int(math.Ceil(bv.Value * float64(canvasBox.Width())))
227 barBox := Box{
228 Top: boxTop,
229 Left: MinInt(xOffset-barHeight, canvasBox.Left+DefaultStrokeWidth),
230 Right: xOffset,
231 Bottom: boxBottom,
232 }
233 Draw.Box(r, barBox, bv.Style.InheritFrom(sbc.styleDefaultsStackedBarValue(index)))
234 xOffset -= barHeight
235 }
236
237 // draw the labels
238 xOffset = canvasBox.Right
239 var lx, ly int
240 for index, bv := range normalizedBarComponents {
241 barHeight := int(math.Ceil(bv.Value * float64(canvasBox.Width())))
242
243 if len(bv.Label) > 0 {
244 lx = xOffset - (barHeight / 2)
245 ly = boxTop + ((boxBottom - boxTop) / 2)
246
247 bv.Style.InheritFrom(sbc.styleDefaultsStackedBarValue(index)).WriteToRenderer(r)
248 tb := r.MeasureText(bv.Label)
249 lx = lx - (tb.Width() >> 1)
250 ly = ly + (tb.Height() >> 1)
251
252 if lx < 0 {
253 lx = 0
254 }
255 if ly < 0 {
256 lx = 0
257 }
258
259 r.Text(bv.Label, lx, ly)
260 }
261 xOffset -= barHeight
262 }
263 }
264
265 func (sbc StackedBarChart) drawXAxis(r Renderer, canvasBox Box) {
266 if !sbc.XAxis.Hidden {
267 axisStyle := sbc.XAxis.InheritFrom(sbc.styleDefaultsAxes())
268 axisStyle.WriteToRenderer(r)
269
270 r.MoveTo(canvasBox.Left, canvasBox.Bottom)
271 r.LineTo(canvasBox.Right, canvasBox.Bottom)
272 r.Stroke()
273
274 r.MoveTo(canvasBox.Left, canvasBox.Bottom)
275 r.LineTo(canvasBox.Left, canvasBox.Bottom+DefaultVerticalTickHeight)
276 r.Stroke()
277
278 cursor := canvasBox.Left
279 for _, bar := range sbc.Bars {
280
281 barLabelBox := Box{
282 Top: canvasBox.Bottom + DefaultXAxisMargin,
283 Left: cursor,
284 Right: cursor + bar.GetWidth() + sbc.GetBarSpacing(),
285 Bottom: sbc.GetHeight(),
286 }
287 if len(bar.Name) > 0 {
288 Draw.TextWithin(r, bar.Name, barLabelBox, axisStyle)
289 }
290 axisStyle.WriteToRenderer(r)
291 r.MoveTo(barLabelBox.Right, canvasBox.Bottom)
292 r.LineTo(barLabelBox.Right, canvasBox.Bottom+DefaultVerticalTickHeight)
293 r.Stroke()
294 cursor += bar.GetWidth() + sbc.GetBarSpacing()
295 }
296 }
297 }
298
299 func (sbc StackedBarChart) drawHorizontalXAxis(r Renderer, canvasBox Box) {
300 if !sbc.XAxis.Hidden {
301 axisStyle := sbc.XAxis.InheritFrom(sbc.styleDefaultsAxes())
302 axisStyle.WriteToRenderer(r)
303 r.MoveTo(canvasBox.Left, canvasBox.Bottom)
304 r.LineTo(canvasBox.Right, canvasBox.Bottom)
305 r.Stroke()
306
307 r.MoveTo(canvasBox.Left, canvasBox.Bottom)
308 r.LineTo(canvasBox.Left, canvasBox.Bottom+DefaultVerticalTickHeight)
309 r.Stroke()
310
311 ticks := LinearRangeWithStep(0.0, 1.0, 0.2)
312 for _, t := range ticks {
313 axisStyle.GetStrokeOptions().WriteToRenderer(r)
314 tx := canvasBox.Left + int(t*float64(canvasBox.Width()))
315 r.MoveTo(tx, canvasBox.Bottom)
316 r.LineTo(tx, canvasBox.Bottom+DefaultVerticalTickHeight)
317 r.Stroke()
318
319 axisStyle.GetTextOptions().WriteToRenderer(r)
320 text := fmt.Sprintf("%0.0f%%", t*100)
321
322 textBox := r.MeasureText(text)
323 textX := tx - (textBox.Width() >> 1)
324 textY := canvasBox.Bottom + DefaultXAxisMargin + 10
325
326 if t == 1 {
327 textX = canvasBox.Right - textBox.Width()
328 }
329
330 Draw.Text(r, text, textX, textY, axisStyle)
331 }
332 }
333 }
334
335 func (sbc StackedBarChart) drawYAxis(r Renderer, canvasBox Box) {
336 if !sbc.YAxis.Hidden {
337 axisStyle := sbc.YAxis.InheritFrom(sbc.styleDefaultsAxes())
338 axisStyle.WriteToRenderer(r)
339 r.MoveTo(canvasBox.Right, canvasBox.Top)
340 r.LineTo(canvasBox.Right, canvasBox.Bottom)
341 r.Stroke()
342
343 r.MoveTo(canvasBox.Right, canvasBox.Bottom)
344 r.LineTo(canvasBox.Right+DefaultHorizontalTickWidth, canvasBox.Bottom)
345 r.Stroke()
346
347 ticks := LinearRangeWithStep(0.0, 1.0, 0.2)
348 for _, t := range ticks {
349 axisStyle.GetStrokeOptions().WriteToRenderer(r)
350 ty := canvasBox.Bottom - int(t*float64(canvasBox.Height()))
351 r.MoveTo(canvasBox.Right, ty)
352 r.LineTo(canvasBox.Right+DefaultHorizontalTickWidth, ty)
353 r.Stroke()
354
355 axisStyle.GetTextOptions().WriteToRenderer(r)
356 text := fmt.Sprintf("%0.0f%%", t*100)
357
358 tb := r.MeasureText(text)
359 Draw.Text(r, text, canvasBox.Right+DefaultYAxisMargin+5, ty+(tb.Height()>>1), axisStyle)
360 }
361 }
362 }
363
364 func (sbc StackedBarChart) drawHorizontalYAxis(r Renderer, canvasBox Box) {
365 if !sbc.YAxis.Hidden {
366 axisStyle := sbc.YAxis.InheritFrom(sbc.styleDefaultsHorizontalAxes())
367 axisStyle.WriteToRenderer(r)
368
369 r.MoveTo(canvasBox.Left, canvasBox.Bottom)
370 r.LineTo(canvasBox.Left, canvasBox.Top)
371 r.Stroke()
372
373 r.MoveTo(canvasBox.Left, canvasBox.Bottom)
374 r.LineTo(canvasBox.Left-DefaultHorizontalTickWidth, canvasBox.Bottom)
375 r.Stroke()
376
377 cursor := canvasBox.Top
378 for _, bar := range sbc.Bars {
379 barLabelBox := Box{
380 Top: cursor,
381 Left: 0,
382 Right: canvasBox.Left - DefaultYAxisMargin,
383 Bottom: cursor + bar.GetWidth() + sbc.GetBarSpacing(),
384 }
385 if len(bar.Name) > 0 {
386 Draw.TextWithin(r, bar.Name, barLabelBox, axisStyle)
387 }
388 axisStyle.WriteToRenderer(r)
389 r.MoveTo(canvasBox.Left, barLabelBox.Bottom)
390 r.LineTo(canvasBox.Left-DefaultHorizontalTickWidth, barLabelBox.Bottom)
391 r.Stroke()
392 cursor += bar.GetWidth() + sbc.GetBarSpacing()
393 }
394 }
395 }
396
397 func (sbc StackedBarChart) drawTitle(r Renderer) {
398 if len(sbc.Title) > 0 && !sbc.TitleStyle.Hidden {
399 r.SetFont(sbc.TitleStyle.GetFont(sbc.GetFont()))
400 r.SetFontColor(sbc.TitleStyle.GetFontColor(sbc.GetColorPalette().TextColor()))
401 titleFontSize := sbc.TitleStyle.GetFontSize(DefaultTitleFontSize)
402 r.SetFontSize(titleFontSize)
403
404 textBox := r.MeasureText(sbc.Title)
405
406 textWidth := textBox.Width()
407 textHeight := textBox.Height()
408
409 titleX := (sbc.GetWidth() >> 1) - (textWidth >> 1)
410 titleY := sbc.TitleStyle.Padding.GetTop(DefaultTitleTop) + textHeight
411
412 r.Text(sbc.Title, titleX, titleY)
413 }
414 }
415
416 func (sbc StackedBarChart) getCanvasStyle() Style {
417 return sbc.Canvas.InheritFrom(sbc.styleDefaultsCanvas())
418 }
419
420 func (sbc StackedBarChart) styleDefaultsCanvas() Style {
421 return Style{
422 FillColor: sbc.GetColorPalette().CanvasColor(),
423 StrokeColor: sbc.GetColorPalette().CanvasStrokeColor(),
424 StrokeWidth: DefaultCanvasStrokeWidth,
425 }
426 }
427
428 // GetColorPalette returns the color palette for the chart.
429 func (sbc StackedBarChart) GetColorPalette() ColorPalette {
430 if sbc.ColorPalette != nil {
431 return sbc.ColorPalette
432 }
433 return AlternateColorPalette
434 }
435
436 func (sbc StackedBarChart) getDefaultCanvasBox() Box {
437 return sbc.Box()
438 }
439
440 func (sbc StackedBarChart) getAdjustedCanvasBox(r Renderer, canvasBox Box) Box {
441 var totalWidth int
442 for _, bar := range sbc.Bars {
443 totalWidth += bar.GetWidth() + sbc.GetBarSpacing()
444 }
445
446 if !sbc.XAxis.Hidden {
447 xaxisHeight := DefaultVerticalTickHeight
448
449 axisStyle := sbc.XAxis.InheritFrom(sbc.styleDefaultsAxes())
450 axisStyle.WriteToRenderer(r)
451
452 cursor := canvasBox.Left
453 for _, bar := range sbc.Bars {
454 if len(bar.Name) > 0 {
455 barLabelBox := Box{
456 Top: canvasBox.Bottom + DefaultXAxisMargin,
457 Left: cursor,
458 Right: cursor + bar.GetWidth() + sbc.GetBarSpacing(),
459 Bottom: sbc.GetHeight(),
460 }
461 lines := Text.WrapFit(r, bar.Name, barLabelBox.Width(), axisStyle)
462 linesBox := Text.MeasureLines(r, lines, axisStyle)
463
464 xaxisHeight = MaxInt(linesBox.Height()+(2*DefaultXAxisMargin), xaxisHeight)
465 }
466 }
467 return Box{
468 Top: canvasBox.Top,
469 Left: canvasBox.Left,
470 Right: canvasBox.Left + totalWidth,
471 Bottom: sbc.GetHeight() - xaxisHeight,
472 }
473 }
474 return Box{
475 Top: canvasBox.Top,
476 Left: canvasBox.Left,
477 Right: canvasBox.Left + totalWidth,
478 Bottom: canvasBox.Bottom,
479 }
480
481 }
482
483 func (sbc StackedBarChart) getHorizontalAdjustedCanvasBox(r Renderer, canvasBox Box) Box {
484 var totalHeight int
485 for _, bar := range sbc.Bars {
486 totalHeight += bar.GetWidth() + sbc.GetBarSpacing()
487 }
488
489 if !sbc.YAxis.Hidden {
490 yAxisWidth := DefaultHorizontalTickWidth
491
492 axisStyle := sbc.YAxis.InheritFrom(sbc.styleDefaultsHorizontalAxes())
493 axisStyle.WriteToRenderer(r)
494
495 cursor := canvasBox.Top
496 for _, bar := range sbc.Bars {
497 if len(bar.Name) > 0 {
498 barLabelBox := Box{
499 Top: cursor,
500 Left: 0,
501 Right: canvasBox.Left + DefaultYAxisMargin,
502 Bottom: cursor + bar.GetWidth() + sbc.GetBarSpacing(),
503 }
504 lines := Text.WrapFit(r, bar.Name, barLabelBox.Width(), axisStyle)
505 linesBox := Text.MeasureLines(r, lines, axisStyle)
506
507 yAxisWidth = MaxInt(linesBox.Height()+(2*DefaultXAxisMargin), yAxisWidth)
508 }
509 }
510 return Box{
511 Top: canvasBox.Top,
512 Left: canvasBox.Left + yAxisWidth,
513 Right: canvasBox.Right,
514 Bottom: canvasBox.Top + totalHeight,
515 }
516 }
517 return Box{
518 Top: canvasBox.Top,
519 Left: canvasBox.Left,
520 Right: canvasBox.Right,
521 Bottom: canvasBox.Top + totalHeight,
522 }
523 }
524
525 // Box returns the chart bounds as a box.
526 func (sbc StackedBarChart) Box() Box {
527 dpr := sbc.Background.Padding.GetRight(10)
528 dpb := sbc.Background.Padding.GetBottom(50)
529
530 return Box{
531 Top: sbc.Background.Padding.GetTop(20),
532 Left: sbc.Background.Padding.GetLeft(20),
533 Right: sbc.GetWidth() - dpr,
534 Bottom: sbc.GetHeight() - dpb,
535 }
536 }
537
538 func (sbc StackedBarChart) styleDefaultsStackedBarValue(index int) Style {
539 return Style{
540 StrokeColor: sbc.GetColorPalette().GetSeriesColor(index),
541 StrokeWidth: 3.0,
542 FillColor: sbc.GetColorPalette().GetSeriesColor(index),
543 FontSize: sbc.getScaledFontSize(),
544 FontColor: sbc.GetColorPalette().TextColor(),
545 Font: sbc.GetFont(),
546 }
547 }
548
549 func (sbc StackedBarChart) styleDefaultsTitle() Style {
550 return sbc.TitleStyle.InheritFrom(Style{
551 FontColor: DefaultTextColor,
552 Font: sbc.GetFont(),
553 FontSize: sbc.getTitleFontSize(),
554 TextHorizontalAlign: TextHorizontalAlignCenter,
555 TextVerticalAlign: TextVerticalAlignTop,
556 TextWrap: TextWrapWord,
557 })
558 }
559
560 func (sbc StackedBarChart) getScaledFontSize() float64 {
561 effectiveDimension := MinInt(sbc.GetWidth(), sbc.GetHeight())
562 if effectiveDimension >= 2048 {
563 return 48.0
564 } else if effectiveDimension >= 1024 {
565 return 24.0
566 } else if effectiveDimension > 512 {
567 return 18.0
568 } else if effectiveDimension > 256 {
569 return 12.0
570 }
571 return 10.0
572 }
573
574 func (sbc StackedBarChart) getTitleFontSize() float64 {
575 effectiveDimension := MinInt(sbc.GetWidth(), sbc.GetHeight())
576 if effectiveDimension >= 2048 {
577 return 48
578 } else if effectiveDimension >= 1024 {
579 return 24
580 } else if effectiveDimension >= 512 {
581 return 18
582 } else if effectiveDimension >= 256 {
583 return 12
584 }
585 return 10
586 }
587
588 func (sbc StackedBarChart) styleDefaultsAxes() Style {
589 return Style{
590 StrokeColor: DefaultAxisColor,
591 Font: sbc.GetFont(),
592 FontSize: DefaultAxisFontSize,
593 FontColor: DefaultAxisColor,
594 TextHorizontalAlign: TextHorizontalAlignCenter,
595 TextVerticalAlign: TextVerticalAlignTop,
596 TextWrap: TextWrapWord,
597 }
598 }
599
600 func (sbc StackedBarChart) styleDefaultsHorizontalAxes() Style {
601 return Style{
602 StrokeColor: DefaultAxisColor,
603 Font: sbc.GetFont(),
604 FontSize: DefaultAxisFontSize,
605 FontColor: DefaultAxisColor,
606 TextHorizontalAlign: TextHorizontalAlignCenter,
607 TextVerticalAlign: TextVerticalAlignMiddle,
608 TextWrap: TextWrapWord,
609 }
610 }
611
612 func (sbc StackedBarChart) styleDefaultsElements() Style {
613 return Style{
614 Font: sbc.GetFont(),
615 }
616 }