Skip to content

Commit

Permalink
all: add AutoRescale to Axis
Browse files Browse the repository at this point in the history
This CL adds a new field to Axis to allow for a better interaction
between a plot, an axis and its ticker, in order to automatically adapt
the range of a given axis.

Signed-off-by: Sebastien Binet <binet@cern.ch>
  • Loading branch information
sbinet committed Jun 5, 2023
1 parent a10bf61 commit d718b18
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
12 changes: 12 additions & 0 deletions axis.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ type Axis struct {
// to the normalized coordinate system of the axis—its distance
// along the axis as a fraction of the axis range.
Scale Normalizer

// AutoRescale enables an axis to automatically adapt its minimum
// and maximum boundaries, according to its underlying Ticker.
AutoRescale bool
}

// makeAxis returns a default Axis.
Expand Down Expand Up @@ -161,6 +165,14 @@ func (a *Axis) sanitizeRange() {
a.Min--
a.Max++
}

if a.AutoRescale {
marks := a.Tick.Marker.Ticks(a.Min, a.Max)
for _, t := range marks {
a.Min = math.Min(a.Min, t.Value)
a.Max = math.Max(a.Max, t.Value)
}
}
}

// LinearScale an be used as the value of an Axis.Scale function to
Expand Down
31 changes: 31 additions & 0 deletions plotter/logscale_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,34 @@ func Example_logScale() {
log.Panic(err)
}
}

// Example_logScaleWithAutoRescale shows how to create a plot with a log-scale on the Y-axis.
// The Y-axis is instructed to automatically adapt its range according to
// the underlying Y-ticker.
func Example_logScaleWithAutoRescale() {
p := plot.New()
p.Title.Text = "My Plot"
p.Y.Scale = plot.LogScale{}
p.Y.Tick.Marker = plot.LogTicks{Prec: -1}
p.Y.AutoRescale = true
p.X.Label.Text = "x"
p.Y.Label.Text = "f(x)"

f := plotter.NewFunction(math.Exp)
f.XMin = 0.2
f.XMax = 10
f.Color = color.RGBA{R: 255, A: 255}

p.Add(f, plotter.NewGrid())
p.Legend.Add("exp(x)", f)

p.X.Min = f.XMin
p.X.Max = f.XMax
p.Y.Min = math.Exp(f.XMin)
p.Y.Max = math.Exp(f.XMax)

err := p.Save(10*vg.Centimeter, 10*vg.Centimeter, "testdata/logscale_autorescale.png")
if err != nil {
log.Panic(err)
}
}
4 changes: 4 additions & 0 deletions plotter/logscale_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ import (
func TestLogScale(t *testing.T) {
cmpimg.CheckPlot(Example_logScale, t, "logscale.png")
}

func TestLogScaleWithAutoRescale(t *testing.T) {
cmpimg.CheckPlot(Example_logScaleWithAutoRescale, t, "logscale_autorescale.png")
}
Binary file added plotter/testdata/logscale_autorescale_golden.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit d718b18

Please sign in to comment.