diff --git a/axis.go b/axis.go index 42569a3..c632815 100644 --- a/axis.go +++ b/axis.go @@ -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, diff --git a/axis_test.go b/axis_test.go index 8396e8a..cc50864 100644 --- a/axis_test.go +++ b/axis_test.go @@ -138,7 +138,7 @@ func TestSetYAxisOption(t *testing.T) { Max: &max, } yAxis := &chart.YAxis{ - Range: &chart.ContinuousRange{}, + Range: newYContinuousRange(opt), } setYAxisOption(yAxis, opt) diff --git a/range.go b/range.go index f1869da..4e00c60 100644 --- a/range.go +++ b/range.go @@ -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) +}