go-chart/tick.go

83 lines
1.9 KiB
Go
Raw Permalink Normal View History

2016-07-10 10:11:47 +02:00
package chart
2016-07-24 00:35:49 +02:00
import "math"
2016-07-13 20:50:22 +02:00
2016-07-24 00:35:49 +02:00
// TicksProvider is a type that provides ticks.
type TicksProvider interface {
2016-08-01 01:54:09 +02:00
GetTicks(r Renderer, defaults Style, vf ValueFormatter) []Tick
2016-07-11 08:06:14 +02:00
}
2016-07-10 10:11:47 +02:00
// 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
}
2016-07-24 00:35:49 +02:00
2016-07-30 21:57:18 +02:00
// GenerateContinuousTicks generates a set of ticks.
func GenerateContinuousTicks(r Renderer, ra Range, isVertical bool, style Style, vf ValueFormatter) []Tick {
2016-08-06 01:55:55 +02:00
if vf == nil {
panic("vf is nil; did you remember to set a default value formatter?")
}
2016-07-24 00:35:49 +02:00
var ticks []Tick
min, max := ra.GetMin(), ra.GetMax()
2016-07-30 21:57:18 +02:00
ticks = append(ticks, Tick{
Value: min,
Label: vf(min),
})
minLabel := vf(min)
style.GetTextOptions().WriteToRenderer(r)
labelBox := r.MeasureText(minLabel)
var tickSize int
if isVertical {
tickSize = labelBox.Height() + DefaultMinimumTickVerticalSpacing
} else {
tickSize = labelBox.Width() + DefaultMinimumTickHorizontalSpacing
2016-07-24 00:35:49 +02:00
}
2016-07-30 21:57:18 +02:00
domainRemainder := (ra.GetDomain()) - (tickSize * 2)
intermediateTickCount := int(math.Floor(float64(domainRemainder) / float64(tickSize)))
2016-07-31 05:30:19 +02:00
rangeDelta := max - min
2016-07-30 21:57:18 +02:00
tickStep := rangeDelta / float64(intermediateTickCount)
roundTo := Math.GetRoundToForDelta(rangeDelta) / 10
2016-07-31 05:30:19 +02:00
intermediateTickCount = Math.MinInt(intermediateTickCount, 1<<10)
2016-07-30 21:57:18 +02:00
for x := 1; x < intermediateTickCount; x++ {
2016-07-31 05:30:19 +02:00
tickValue := min + Math.RoundUp(tickStep*float64(x), roundTo)
ticks = append(ticks, Tick{
2016-07-30 21:57:18 +02:00
Value: tickValue,
Label: vf(tickValue),
})
}
2016-07-24 00:35:49 +02:00
2016-07-30 21:57:18 +02:00
ticks = append(ticks, Tick{
Value: max,
Label: vf(max),
})
2016-07-24 00:35:49 +02:00
2016-07-30 21:57:18 +02:00
return ticks
2016-07-24 00:35:49 +02:00
}