plot

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2024 License: BSD-3-Clause Imports: 16 Imported by: 0

README

Plot

The plot package generates 2D plots of data using the Cogent Core paint rendering system. The plotview sub-package has Cogent Core Widgets that can be used in applications.

  • Plot is just a wrapper around a plot.Plot, for manually-configured plots.
  • PlotView is an interactive plot viewer that supports selection of which data to plot, and configuration of many plot parameters.

The code is adapted from the gonum plot package (which in turn was adapted from google's plotinum, to use the Cogent Core styles and paint rendering framework, which also supports SVG output of the rendering.

Here is the copyright notice for that package:

// Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInfinity = errors.New("plotter: infinite data point")
	ErrNoData   = errors.New("plotter: no data points")
)
View Source
var DefaultFontFamily = ""

DefaultFontFamily specifies a default font for plotting. if not set, the standard Cogent Core default font is used.

View Source
var UTCUnixTime = UnixTimeIn(time.UTC)

UTCUnixTime is the default time conversion for TimeTicks.

Functions

func CheckFloats

func CheckFloats(fs ...float32) error

CheckFloats returns an error if any of the arguments are Infinity. or if there are no non-NaN data points available for plotting.

func CheckNaNs

func CheckNaNs(fs ...float32) bool

CheckNaNs returns true if any of the floats are NaN

func Range

func Range(vs Valuer) (min, max float32)

Range returns the minimum and maximum values.

func UnixTimeIn

func UnixTimeIn(loc *time.Location) func(t float32) time.Time

UnixTimeIn returns a time conversion function for the given location.

func XYRange

func XYRange(xys XYer) (xmin, xmax, ymin, ymax float32)

XYRange returns the minimum and maximum x and y values.

Types

type Axis

type Axis struct {
	// Min and Max are the minimum and maximum data
	// values represented by the axis.
	Min, Max float32

	// specifies which axis this is: X or Y
	Axis math32.Dims

	// Label for the axis
	Label Text

	// Line styling properties for the axis line.
	Line LineStyle

	// Padding between the axis line and the data.  Having
	// non-zero padding ensures that the data is never drawn
	// on the axis, thus making it easier to see.
	Padding units.Value

	// has the text style for rendering tick labels, and is shared for actual rendering
	TickText Text

	// line style for drawing tick lines
	TickLine LineStyle

	// length of tick lines
	TickLength units.Value

	// Ticker generates the tick marks.  Any tick marks
	// returned by the Marker function that are not in
	// range of the axis are not drawn.
	Ticker Ticker

	// Scale transforms a value given in the data coordinate system
	// 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
	// contains filtered or unexported fields
}

Axis represents either a horizontal or vertical axis of a plot.

func (*Axis) Defaults

func (ax *Axis) Defaults(dim math32.Dims)

Sets Defaults, range is (∞, ­∞), and thus any finite value is less than Min and greater than Max.

func (*Axis) Norm

func (ax *Axis) Norm(x float32) float32

Norm returns the value of x, given in the data coordinate system, normalized to its distance as a fraction of the range of this axis. For example, if x is a.Min then the return value is 0, and if x is a.Max then the return value is 1.

func (*Axis) SanitizeRange

func (ax *Axis) SanitizeRange()

SanitizeRange ensures that the range of the axis makes sense.

type ConstantTicks

type ConstantTicks []Tick

ConstantTicks is suitable for the Ticker field of an Axis. This function returns the given set of ticks.

func (ConstantTicks) Ticks

func (ts ConstantTicks) Ticks(float32, float32) []Tick

Ticks returns Ticks in a specified range

type DataRanger

type DataRanger interface {
	// DataRange returns the range of X and Y values.
	DataRange() (xmin, xmax, ymin, ymax float32)
}

DataRanger wraps the DataRange method.

type DefaultTicks

type DefaultTicks struct{}

DefaultTicks is suitable for the Ticker field of an Axis, it returns a reasonable default set of tick marks.

func (DefaultTicks) Ticks

func (DefaultTicks) Ticks(min, max float32) []Tick

Ticks returns Ticks in the specified range.

type InvertedScale

type InvertedScale struct{ Normalizer }

InvertedScale can be used as the value of an Axis.Scale function to invert the axis using any Normalizer.

func (InvertedScale) Normalize

func (is InvertedScale) Normalize(min, max, x float32) float32

Normalize returns a normalized [0, 1] value for the position of x.

type Labeller

type Labeller interface {
	// Label returns a label.
	Label(i int) string
}

Labeller provides an interface for a list of string labels

type Legend

type Legend struct {
	// TextStyle is the style given to the legend entry texts.
	TextStyle TextStyle

	// position of the legend
	Position LegendPosition `view:"inline"`

	// ThumbnailWidth is the width of legend thumbnails.
	ThumbnailWidth units.Value

	// FillColor specifies the background fill color for the legend box,
	// if non-nil.
	FillColor color.Color

	// Entries are all of the LegendEntries described by this legend.
	Entries []LegendEntry
}

A Legend gives a description of the meaning of different data elements of the plot. Each legend entry has a name and a thumbnail, where the thumbnail shows a small sample of the display style of the corresponding data.

func (*Legend) Add

func (lg *Legend) Add(name string, thumbs ...Thumbnailer)

Add adds an entry to the legend with the given name. The entry's thumbnail is drawn as the composite of all of the thumbnails.

func (*Legend) Defaults

func (lg *Legend) Defaults()

type LegendEntry

type LegendEntry struct {
	// text is the text associated with this entry.
	Text string

	// thumbs is a slice of all of the thumbnails styles
	Thumbs []Thumbnailer
}

A LegendEntry represents a single line of a legend, it has a name and an icon.

type LegendPosition

type LegendPosition struct {
	// Top and Left specify the location of the legend.
	Top, Left bool

	// XOffs and YOffs are added to the legend's final position,
	// relative to the relevant anchor position
	XOffs, YOffs units.Value
}

LegendPosition specifies where to put the legend

func (*LegendPosition) Defaults

func (lg *LegendPosition) Defaults()

type LineStyle

type LineStyle struct {

	// stroke color image specification; stroking is off if nil
	Color image.Image

	// line width
	Width units.Value

	// Dashes are the dashes of the stroke. Each pair of values specifies
	// the amount to paint and then the amount to skip.
	Dashes []float32
}

LineStyle has style properties for line drawing

func (*LineStyle) Defaults

func (ls *LineStyle) Defaults()

func (*LineStyle) Draw

func (ls *LineStyle) Draw(pt *Plot, start, end math32.Vector2) bool

Draw draws a line between given coordinates, setting the stroke style to current parameters. Returns false if either Width = 0 or Color = nil

func (*LineStyle) SetStroke

func (ls *LineStyle) SetStroke(pt *Plot) bool

SetStroke sets the stroke style in plot paint to current line style. returns false if either the Width = 0 or Color is nil

type LinearScale

type LinearScale struct{}

LinearScale an be used as the value of an Axis.Scale function to set the axis to a standard linear scale.

func (LinearScale) Normalize

func (LinearScale) Normalize(min, max, x float32) float32

Normalize returns the fractional distance of x between min and max.

type LogScale

type LogScale struct{}

LogScale can be used as the value of an Axis.Scale function to set the axis to a log scale.

func (LogScale) Normalize

func (LogScale) Normalize(min, max, x float32) float32

Normalize returns the fractional logarithmic distance of x between min and max.

type LogTicks

type LogTicks struct {
	// Prec specifies the precision of tick rendering
	// according to the documentation for strconv.FormatFloat.
	Prec int
}

LogTicks is suitable for the Ticker field of an Axis, it returns tick marks suitable for a log-scale axis.

func (LogTicks) Ticks

func (t LogTicks) Ticks(min, max float32) []Tick

Ticks returns Ticks in a specified range

type Normalizer

type Normalizer interface {
	// Normalize transforms a value x in the data coordinate system to
	// the normalized coordinate system.
	Normalize(min, max, x float32) float32
}

Normalizer rescales values from the data coordinate system to the normalized coordinate system.

type Plot

type Plot struct {
	// Title of the plot
	Title Text

	// Background is the background color of the plot.
	// The default is White.
	Background color.Color

	// standard text style with default params
	StdTextStyle styles.Text

	// X and Y are the horizontal and vertical axes
	// of the plot respectively.
	X, Y Axis

	// Legend is the plot's legend.
	Legend Legend

	// plotters are drawn by calling their Plot method
	// after the axes are drawn.
	Plotters []Plotter

	// size is the target size of the image to render to
	Size image.Point

	// DPI is the dots per inch for rendering the image.
	// Larger numbers result in larger scaling of the plot contents
	// which is strongly recommended for print (e.g., use 300 for print)
	DPI float32 `default:"96,160,300"`

	// painter for rendering
	Paint *paint.Context

	// pixels that we render into
	Pixels *image.RGBA `copier:"-" json:"-" xml:"-" edit:"-"`

	// Current plot bounding box in image coordinates, for plotting coordinates
	PlotBox math32.Box2
}

Plot is the basic type representing a plot. It renders into its own image.RGBA Pixels image, and can also save a corresponding SVG version. The Axis ranges are updated automatically when plots are added, so setting a fixed range should happen after that point. See [UpdateRange] method as well.

func New

func New() *Plot

New returns a new plot with some reasonable default settings.

func (*Plot) Add

func (pt *Plot) Add(ps ...Plotter)

Add adds a Plotters to the plot.

If the plotters implements DataRanger then the minimum and maximum values of the X and Y axes are changed if necessary to fit the range of the data.

When drawing the plot, Plotters are drawn in the order in which they were added to the plot.

func (*Plot) ClosestDataToPixel

func (pt *Plot) ClosestDataToPixel(px, py int) (plt Plotter, idx int, dist float32, data, pixel math32.Vector2)

ClosestDataToPixel returns the Plotter data point closest to given pixel point, in the Pixels image.

func (*Plot) Defaults

func (pt *Plot) Defaults()

Defaults sets defaults

func (*Plot) Draw

func (pt *Plot) Draw()

Draw draws the plot to image. Plotters are drawn in the order in which they were added to the plot.

func (*Plot) HideAxes

func (pt *Plot) HideAxes()

HideAxes hides the X and Y axes.

func (*Plot) HideX

func (pt *Plot) HideX()

HideX configures the X axis so that it will not be drawn.

func (*Plot) HideY

func (pt *Plot) HideY()

HideY configures the Y axis so that it will not be drawn.

func (*Plot) NominalX

func (pt *Plot) NominalX(names ...string)

NominalX configures the plot to have a nominal X axis—an X axis with names instead of numbers. The X location corresponding to each name are the integers, e.g., the x value 0 is centered above the first name and 1 is above the second name, etc. Labels for x values that do not end up in range of the X axis will not have tick marks.

func (*Plot) NominalY

func (pt *Plot) NominalY(names ...string)

NominalY is like NominalX, but for the Y axis.

func (*Plot) PX

func (pt *Plot) PX(v float32) float32

PX returns the X-axis plotting coordinate for given raw data value using the current plot bounding region

func (*Plot) PY

func (pt *Plot) PY(v float32) float32

PY returns the Y-axis plotting coordinate for given raw data value

func (*Plot) Resize

func (pt *Plot) Resize(sz image.Point)

Resize sets the size of the output image to given size. Does nothing if already the right size.

func (*Plot) SVGString

func (pt *Plot) SVGString() string

SVGString returns an SVG representation of the plot as a string

func (*Plot) SVGToFile

func (pt *Plot) SVGToFile(filename string) error

SVGToFile saves the SVG to given file

func (*Plot) SaveImage

func (pt *Plot) SaveImage(filename string) error

func (*Plot) SetPixels added in v0.1.3

func (pt *Plot) SetPixels(img *image.RGBA)

SetPixels sets the backing pixels image to given image.RGBA

func (*Plot) UpdateRange

func (pt *Plot) UpdateRange()

UpdateRange updates the axis range values based on current Plot values. This first resets the range so any fixed additional range values should be set after this point.

func (*Plot) UpdateRangeFromPlotter

func (pt *Plot) UpdateRangeFromPlotter(d Plotter)

type Plotter

type Plotter interface {
	// Plot draws the data to the Plot Paint
	Plot(pt *Plot)

	// returns the data for this plot as X,Y points,
	// including corresponding pixel data.
	// This allows gui interface to inspect data etc.
	XYData() (data XYer, pixels XYer)
}

Plotter is an interface that wraps the Plot method. Some standard implementations of Plotter can be found in plotters.

type Text

type Text struct {

	// text string, which can use HTML formatting
	Text string

	// styling for this text element
	Style TextStyle

	// PaintText is the [paint.Text] for the text.
	PaintText paint.Text
}

Text specifies a single text element in a plot

func (*Text) Config

func (tx *Text) Config(pt *Plot)

config is called during the layout of the plot, prior to drawing

func (*Text) Defaults

func (tx *Text) Defaults()

func (*Text) Draw

func (tx *Text) Draw(pt *Plot, pos math32.Vector2)

Draw renders the text at given upper left position

func (*Text) PosX

func (tx *Text) PosX(width float32) math32.Vector2

PosX returns the starting position for a horizontally-aligned text element, based on given width. Text must have been config'd already.

func (*Text) PosY

func (tx *Text) PosY(height float32) math32.Vector2

PosY returns the starting position for a vertically-rotated text element, based on given height. Text must have been config'd already.

type TextStyle

type TextStyle struct {
	styles.FontRender

	// how to align text along the relevant dimension for the text element
	Align styles.Aligns

	// Padding is used in a case-dependent manner to add space around text elements
	Padding units.Value

	// rotation of the text, in Degrees
	Rotation float32
}

TextStyle specifies styling parameters for Text elements

func (*TextStyle) Defaults

func (ts *TextStyle) Defaults()

func (*TextStyle) ToDots

func (ts *TextStyle) ToDots(uc *units.Context)

type Thumbnailer

type Thumbnailer interface {
	// Thumbnail draws an thumbnail representing
	// a legend entry.  The thumbnail will usually show
	// a smaller representation of the style used
	// to plot the corresponding data.
	Thumbnail(pt *Plot)
}

Thumbnailer wraps the Thumbnail method, which draws the small image in a legend representing the style of data.

type Tick

type Tick struct {
	// Value is the data value marked by this Tick.
	Value float32

	// Label is the text to display at the tick mark.
	// If Label is an empty string then this is a minor tick mark.
	Label string
}

A Tick is a single tick mark on an axis.

func (*Tick) IsMinor

func (tk *Tick) IsMinor() bool

IsMinor returns true if this is a minor tick mark.

type Ticker

type Ticker interface {
	// Ticks returns Ticks in a specified range
	Ticks(min, max float32) []Tick
}

Ticker creates Ticks in a specified range

type TickerFunc

type TickerFunc func(min, max float32) []Tick

TickerFunc is suitable for the Ticker field of an Axis. It is an adapter which allows to quickly setup a Ticker using a function with an appropriate signature.

func (TickerFunc) Ticks

func (f TickerFunc) Ticks(min, max float32) []Tick

Ticks implements plot.Ticker.

type TimeTicks

type TimeTicks struct {
	// Ticker is used to generate a set of ticks.
	// If nil, DefaultTicks will be used.
	Ticker Ticker

	// Format is the textual representation of the time value.
	// If empty, time.RFC3339 will be used
	Format string

	// Time takes a float32 value and converts it into a time.Time.
	// If nil, UTCUnixTime is used.
	Time func(t float32) time.Time
}

TimeTicks is suitable for axes representing time values.

func (TimeTicks) Ticks

func (t TimeTicks) Ticks(min, max float32) []Tick

Ticks implements plot.Ticker.

type Valuer

type Valuer interface {
	// Len returns the number of values.
	Len() int

	// Value returns a value.
	Value(i int) float32
}

Valuer provides an interface for a list of scalar values

type Values

type Values []float32

Values implements the Valuer interface.

func CopyValues

func CopyValues(vs Valuer) (Values, error)

CopyValues returns a Values that is a copy of the values from a Valuer, or an error if there are no values, or if one of the copied values is a Infinity. NaN values are skipped in the copying process.

func (Values) Len

func (vs Values) Len() int

func (Values) Value

func (vs Values) Value(i int) float32

type XValues

type XValues struct {
	XYer
}

XValues implements the Valuer interface, returning the x value from an XYer.

func (XValues) Value

func (xs XValues) Value(i int) float32

type XYValues

type XYValues struct{ XYZer }

XYValues implements the XYer interface, returning the x and y values from an XYZer.

func (XYValues) XY

func (xy XYValues) XY(i int) (float32, float32)

XY implements the XY method of the XYer interface.

type XYZ

type XYZ struct{ X, Y, Z float32 }

XYZ is an x, y and z value.

type XYZer

type XYZer interface {
	// Len returns the number of x, y, z triples.
	Len() int

	// XYZ returns an x, y, z triple.
	XYZ(i int) (float32, float32, float32)

	// XY returns an x, y pair.
	XY(i int) (float32, float32)
}

XYZer provides an interface for a list of X,Y,Z data triples. It also satisfies the XYer interface for the X,Y pairs.

type XYZs

type XYZs []XYZ

XYZs implements the XYZer interface using a slice.

func CopyXYZs

func CopyXYZs(data XYZer) (XYZs, error)

CopyXYZs copies an XYZer.

func (XYZs) Len

func (xyz XYZs) Len() int

Len implements the Len method of the XYZer interface.

func (XYZs) XY

func (xyz XYZs) XY(i int) (float32, float32)

XY implements the XY method of the XYer interface.

func (XYZs) XYZ

func (xyz XYZs) XYZ(i int) (float32, float32, float32)

XYZ implements the XYZ method of the XYZer interface.

type XYer

type XYer interface {
	// Len returns the number of x, y pairs.
	Len() int

	// XY returns an x, y pair.
	XY(i int) (x, y float32)
}

XYer provides an interface for a list of X,Y data pairs

type XYs

type XYs []math32.Vector2

XYs implements the XYer interface.

func CopyXYs

func CopyXYs(data XYer) (XYs, error)

CopyXYs returns an XYs that is a copy of the x and y values from an XYer, or an error if one of the data points contains a NaN or Infinity.

func PlotXYs

func PlotXYs(plt *Plot, data XYs) XYs

PlotXYs returns plot coordinates for given set of XYs

func (XYs) Len

func (xys XYs) Len() int

func (XYs) XY

func (xys XYs) XY(i int) (float32, float32)

type YValues

type YValues struct {
	XYer
}

YValues implements the Valuer interface, returning the y value from an XYer.

func (YValues) Value

func (ys YValues) Value(i int) float32

Directories

Path Synopsis
Package plots defines a variety of standard Plotters for the plot package.
Package plots defines a variety of standard Plotters for the plot package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL