Debian Codegraph @

tick.go

raw symbols SCIP
1 package chart
2
3 import (
4 "fmt"
5 "math"
6 "strings"
7 )
8
9 // TicksProvider is a type that provides ticks.
10 type TicksProvider interface {
11 GetTicks(r Renderer, defaults Style, vf ValueFormatter) []Tick
12 }
13
14 // Tick represents a label on an axis.
15 type Tick struct {
16 Value float64
17 Label string
18 }
19
20 // Ticks is an array of ticks.
21 type Ticks []Tick
22
23 // Len returns the length of the ticks set.
24 func (t Ticks) Len() int {
25 return len(t)
26 }
27
28 // Swap swaps two elements.
29 func (t Ticks) Swap(i, j int) {
30 t[i], t[j] = t[j], t[i]
31 }
32
33 // Less returns if i's value is less than j's value.
34 func (t Ticks) Less(i, j int) bool {
35 return t[i].Value < t[j].Value
36 }
37
38 // String returns a string representation of the set of ticks.
39 func (t Ticks) String() string {
40 var values []string
41 for i, tick := range t {
42 values = append(values, fmt.Sprintf("[%d: %s]", i, tick.Label))
43 }
44 return strings.Join(values, ", ")
45 }
46
47 // GenerateContinuousTicks generates a set of ticks.
48 func GenerateContinuousTicks(r Renderer, ra Range, isVertical bool, style Style, vf ValueFormatter) []Tick {
49 if vf == nil {
50 vf = FloatValueFormatter
51 }
52
53 var ticks []Tick
54 min, max := ra.GetMin(), ra.GetMax()
55
56 if ra.IsDescending() {
57 ticks = append(ticks, Tick{
58 Value: max,
59 Label: vf(max),
60 })
61 } else {
62 ticks = append(ticks, Tick{
63 Value: min,
64 Label: vf(min),
65 })
66 }
67
68 minLabel := vf(min)
69 style.GetTextOptions().WriteToRenderer(r)
70 labelBox := r.MeasureText(minLabel)
71
72 var tickSize float64
73 if isVertical {
74 tickSize = float64(labelBox.Height() + DefaultMinimumTickVerticalSpacing)
75 } else {
76 tickSize = float64(labelBox.Width() + DefaultMinimumTickHorizontalSpacing)
77 }
78
79 domain := float64(ra.GetDomain())
80 domainRemainder := domain - (tickSize * 2)
81 intermediateTickCount := int(math.Floor(float64(domainRemainder) / float64(tickSize)))
82
83 rangeDelta := math.Abs(max - min)
84 tickStep := rangeDelta / float64(intermediateTickCount)
85
86 roundTo := GetRoundToForDelta(rangeDelta) / 10
87 intermediateTickCount = MinInt(intermediateTickCount, DefaultTickCountSanityCheck)
88
89 for x := 1; x < intermediateTickCount; x++ {
90 var tickValue float64
91 if ra.IsDescending() {
92 tickValue = max - RoundUp(tickStep*float64(x), roundTo)
93 } else {
94 tickValue = min + RoundUp(tickStep*float64(x), roundTo)
95 }
96 ticks = append(ticks, Tick{
97 Value: tickValue,
98 Label: vf(tickValue),
99 })
100 }
101
102 if ra.IsDescending() {
103 ticks = append(ticks, Tick{
104 Value: min,
105 Label: vf(min),
106 })
107 } else {
108 ticks = append(ticks, Tick{
109 Value: max,
110 Label: vf(max),
111 })
112 }
113
114 return ticks
115 }