feat: enhance set min and max for y axis

This commit is contained in:
vicanso 2021-12-26 09:41:44 +08:00
parent 18af884865
commit 5a437f48d6
3 changed files with 53 additions and 9 deletions

27
axis.go
View file

@ -23,6 +23,8 @@
package charts
import (
"math"
"github.com/dustin/go-humanize"
"github.com/wcharczuk/go-chart/v2"
)
@ -125,11 +127,26 @@ func defaultFloatFormater(v interface{}) string {
return humanize.CommafWithDigits(value, 2)
}
func newYContinuousRange(option *YAxisOption) *YContinuousRange {
m := YContinuousRange{}
m.Min = -math.MaxFloat64
m.Max = math.MaxFloat64
if option != nil {
if option.Min != nil {
m.Min = *option.Min
}
if option.Max != nil {
m.Max = *option.Max
}
}
return &m
}
// GetSecondaryYAxis returns the secondary y axis by theme
func GetSecondaryYAxis(theme string, option *YAxisOption) chart.YAxis {
strokeColor := getGridColor(theme)
yAxis := chart.YAxis{
Range: &chart.ContinuousRange{},
Range: newYContinuousRange(option),
ValueFormatter: defaultFloatFormater,
AxisType: chart.YAxisSecondary,
GridMajorStyle: chart.Style{
@ -158,12 +175,6 @@ func setYAxisOption(yAxis *chart.YAxis, option *YAxisOption) {
if option.Formater != nil {
yAxis.ValueFormatter = option.Formater
}
if option.Max != nil {
yAxis.Range.SetMax(*option.Max)
}
if option.Min != nil {
yAxis.Range.SetMin(*option.Min)
}
}
// GetYAxis returns the primary y axis by theme
@ -175,7 +186,7 @@ func GetYAxis(theme string, option *YAxisOption) chart.YAxis {
hidden := chart.Hidden()
yAxis := chart.YAxis{
Range: &chart.ContinuousRange{},
Range: newYContinuousRange(option),
ValueFormatter: defaultFloatFormater,
AxisType: chart.YAxisPrimary,
GridMajorStyle: hidden,

View file

@ -138,7 +138,7 @@ func TestSetYAxisOption(t *testing.T) {
Max: &max,
}
yAxis := &chart.YAxis{
Range: &chart.ContinuousRange{},
Range: newYContinuousRange(opt),
}
setYAxisOption(yAxis, opt)

View file

@ -23,6 +23,8 @@
package charts
import (
"math"
"github.com/wcharczuk/go-chart/v2"
)
@ -58,3 +60,34 @@ type HiddenRange struct {
func (r HiddenRange) GetDelta() float64 {
return 0
}
// Y轴使用的continuous range
// min 与max只允许设置一次
// 如果是计算得出的max增加20%的值并取整
type YContinuousRange struct {
chart.ContinuousRange
}
func (m YContinuousRange) IsZero() bool {
// 默认返回true允许修改
return true
}
func (m *YContinuousRange) SetMin(min float64) {
// 如果已修改,则忽略
if m.Min != -math.MaxFloat64 {
return
}
m.Min = min
}
func (m *YContinuousRange) SetMax(max float64) {
// 如果已修改,则忽略
if m.Max != math.MaxFloat64 {
return
}
// 此处为计算得来的最大值放大20%
v := int(max * 1.2)
// TODO 是否要取整十整百
m.Max = float64(v)
}