chart

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2021 License: BSD-3-Clause Imports: 6 Imported by: 0

README

Charts for Go

Basic charts in go.

This package focuses more on autoscaling, error bars, and logarithmic plots than on beautifull or marketing ready charts.

Examples

Some nice charts

Chart Types

The following chart types are implemented:

  • Strip Charts
  • Scatter / Function-Plot Charts
  • Histograms
  • Bar and Categorical Bar Charts
  • Pie/Ring Charts
  • Boxplots

Some Features

  • Axis can be linear, logarithmical, categorical or time/date axis.
  • Autoscaling with lots of options
  • Fine control of tics and labels

Output / Graphic Formats

Package chart itself provideds the charts/plots itself, the charts/plots can be output to different graphic drivers. Currently

  • txtg: ASCII art charts
  • svgg: scalable vector graphics (via github.com/ajstarks/svgo), and
  • imgg: Go image.RGBA (via code.google.com/p/draw2d/draw2d/ and code.google.com/p/freetype-go) are implemented.

For a quick overview save as xbestof.{png,svg,txt} run

  $ example/example -best

A fuller overview can be generated by

  $ example/example -All

Quirks

  • Style handling (especialy colour) is a bit of a mess .
  • Text based charts are cute. But the general graphics would be much easier without.
  • Time handling code dates back to pre Go1, it should be reworked.

Documentation

Overview

Package chart implements common chart/plot types.

The following chart types are available:

StripChart       Visualize set of numeric values
ScatterChart     Plot (x,y) data (with optional error bars)
                 and/or functions
HistChart        Produce histograms from data
BarChart         Show (x,y) data as bars
BoxChart         Box charts to visualize distributions
PieChart         Pie and Ring charts

Chart tries to provides useful defaults and produce nice charts without sacrificing accuracy. The generated charts look good and are higly customizable but will not match the visual quality of handmade photoshop charts or the statistical features of charts produced by S or R.

Creating charts consists of the following steps:

  1. Create chart object
  2. Configure chart, axis, autoscaling etc.
  3. Add one ore more data sets
  4. Render chart to one or more graphic outputs

You may change the configuration at any step or render to different outputs.

The different chart types and their fields are all simple struct types where the zero value provides suitable defaults. All fields are exported, even if you are not supposed to manipulate them directy or are 'output fields'. E.g. the common Data field of all chart types will store the sample data added with one or more Add... methods. Some fields are mere output which expose internal stuff for your use like the Data2Screen and Screen2Data functions of the Ranges. Some fields are even input/output fields: E.g. you may set the Range.TicSetting.Delta to some positive value which will be used as the spacing between tics on that axis; on the other hand if you leave Range.TicSetting.Delta at its default 0 you indicate to the plotting routine to automatically determine the tic delta which is then reported back in this fields.

All charts (except pie/ring charts) contain at least one axis represented by a field of type Range. Axis can be differented into following categories:

o  Date/Time axis (Time=true): The values on this axis are interpreted as
   seconds since the Unix epoc, tics are labeld in date and time units.
   (The Log and Category fields are simply ignored for Date/Time axis.)

o  Real valued axis (Time=false).  Those come in different flavours:
     -  Simple linear real valued axis (Log=false, Category=nil).
     -  Logrithmic axis (Log=True).  Such an axis may cover only a
        range of ]0,inf[
     -  Categorical axis (Log=false, Category!=nil):
        The values 0, 1, 2, ... are labeled with the strings in Category.
        (You might want to set up the range manually, e.g. with the
        Fixed() method of Range)

How the axis is autoscaled can be controlled for both ends of the axis individually by MinMode and MaxMode which allow a fine control of the (auto-) scaling.

After setting up the chart, adding data, samples, functions you can render the chart to a Graphics output. This process will set several internal fields of the chart. If you reuse the chart, add additional data and output it again these fields might no longer indicate 'automatical/default' but contain the value calculated in the first output round.

Index

Constants

This section is empty.

Variables

View Source
var (
	KeyHorSep      float32 = 1.5  // Horizontal spacing between key box and content
	KeyVertSep     float32 = 0.5  // Vertical spacing between key box and content
	KeyColSep      float32 = 2.0  // Horizontal spacing between two columns in key
	KeySymbolWidth float32 = 5    // Horizontal length/space reserved for symbol
	KeySymbolSep   float32 = 2    // Horizontal spacing bewteen symbol and text
	KeyRowSep      float32 = 0.75 // Vertical spacing between individual rows.
)

The following variables control the layout of the key/legend box. All values are in font-units (fontheight for vertical, fontwidth for horizontal values)

View Source
var CharacterWidth = map[int]float32{'a': 16.8, 'b': 17.0, 'c': 15.2, 'd': 16.8, 'e': 16.8, 'f': 8.5, 'g': 17.0,
	'h': 16.8, 'i': 5.9, 'j': 5.9, 'k': 16.8, 'l': 6.9, 'm': 25.5, 'n': 16.8, 'o': 16.8, 'p': 17.0, 'q': 17.0,
	'r': 10.2, 's': 15.2, 't': 8.4, 'u': 16.8, 'v': 15.4, 'w': 22.2, 'x': 15.2, 'y': 15.2, 'z': 15.2,
	'A': 20.2, 'B': 20.2, 'C': 22.2, 'D': 22.2, 'E': 20.2, 'F': 18.6, 'G': 23.5, 'H': 22.0, 'I': 8.2, 'J': 15.2,
	'K': 20.2, 'L': 16.8, 'M': 25.5, 'N': 22.0, 'O': 23.5, 'P': 20.2, 'Q': 23.5, 'R': 21.1, 'S': 20.2, 'T': 18.5,
	'U': 22.0, 'V': 20.2, 'W': 29.0, 'X': 20.2, 'Y': 20.2, 'Z': 18.8, ' ': 8.5,
	'1': 16.8, '2': 16.8, '3': 16.8, '4': 16.8, '5': 16.8, '6': 16.8, '7': 16.8, '8': 16.8, '9': 16.8, '0': 16.8,
	'.': 8.2, ',': 8.2, ':': 8.2, ';': 8.2, '+': 17.9, '"': 11.0, '*': 11.8, '%': 27.0, '&': 20.2, '/': 8.4,
	'(': 10.2, ')': 10.2, '=': 18.0, '?': 16.8, '!': 8.5, '[': 8.2, ']': 8.2, '{': 10.2, '}': 10.2, '$': 16.8,
	'<': 18.0, '>': 18.0, '§': 16.8, '°': 12.2, '^': 14.2, '~': 18.0,
}

CharacterWidth is a table of the (relative) width of common runes.

View Source
var DefaultOptions = map[PlotElement]Style{
	MajorAxisElement: Style{LineColor: color.NRGBA{0, 0, 0, 0xff}, LineWidth: 2, LineStyle: SolidLine},
	MinorAxisElement: Style{LineColor: color.NRGBA{0, 0, 0, 0xff}, LineWidth: 2, LineStyle: SolidLine},
	MajorTicElement:  Style{LineColor: color.NRGBA{0, 0, 0, 0xff}, LineWidth: 1, LineStyle: SolidLine},
	MinorTicElement:  Style{LineColor: color.NRGBA{0, 0, 0, 0xff}, LineWidth: 1, LineStyle: SolidLine},
	ZeroAxisElement:  Style{LineColor: color.NRGBA{0x40, 0x40, 0x40, 0xff}, LineWidth: 1, LineStyle: SolidLine},
	GridLineElement:  Style{LineColor: color.NRGBA{0x80, 0x80, 0x80, 0xff}, LineWidth: 1, LineStyle: SolidLine},
	GridBlockElement: Style{LineColor: color.NRGBA{0xe6, 0xfc, 0xfc, 0xff}, LineWidth: 0, FillColor: color.NRGBA{0xe6, 0xfc, 0xfc, 0xff}},
	KeyElement: Style{LineColor: color.NRGBA{0x20, 0x20, 0x20, 0xff}, LineWidth: 1, LineStyle: SolidLine,
		FillColor: color.NRGBA{0xf0, 0xf0, 0xf0, 0xc0}, Font: Font{Size: SmallFontSize}},
	TitleElement: Style{LineColor: color.NRGBA{0, 0, 0, 0xff}, LineWidth: 1, LineStyle: SolidLine,
		FillColor: color.NRGBA{0xec, 0xc7, 0x50, 0xff}, Font: Font{Size: LargeFontSize}},
	RangeLimitElement: Style{Font: Font{Size: SmallFontSize}},
}

DefaultStyle maps chart elements to styles.

View Source
var ExpandABitFraction = 0.5

ExpandABitFraction is the fraction of a major tic spacing added during axis range expansion with the ExpandABit mode.

View Source
var PieChartHighlight = 0.15 // How much are flaged segments offset.
View Source
var PieChartShrinkage = 0.66 // Scaling factor of radius of next data set.
View Source
var StandardColors = []color.Color{}

Standard colors used by AutoStyle

Standard line styles used by AutoStyle (fill=false)

View Source
var StandardSymbols = []int{'o', '=', '%', '&', '+', 'X', '*', '@', '#', 'A', 'Z'}

Standard symbols used by AutoStyle

View Source
var Symbol = []int{
	'o',
	'=',
	'%',
	'&',
	'+',
	'X',
	'*',
	'0',
	'@',
	'#',
	'A',
	'W',
	'V',
	'Z',
	'.',
}

Symbol is the list of different symbols.

View Source
var Units = []string{" y", " z", " a", " f", " p", " n", " µ", "m", " k", " M", " G", " T", " P", " E", " Z", " Y"}

Units are the SI prefixes for 10^3n

Functions

func AbsoluteValue

func AbsoluteValue(value, sum float64) (s string)

AbsoluteValue will format value (ignoring sum). It is a convenience function which can be assigned to the PieChart.FmtVal or PieChart.FmtKey field.

func FmtFloat

func FmtFloat(f float64) string

FmtFloat yields a string representation of f. E.g. 12345.67 --> "12.3 k"; 0.09876 --> "99 m"

func GenericBars

func GenericBars(bg BasicGraphics, bars []Barinfo, style Style)

GenericBars draws the bars in the given style using bg. TODO: Is Bars and Generic Bars useful at all? Replaceable by rect?

func GenericBoxes

func GenericBoxes(bg BasicGraphics, boxes []Box, width int, style Style)

GenericBoxes draws box plots. (Default implementation for box plots). The values for each box in boxes are in screen coordinates!

func GenericCircle

func GenericCircle(bg BasicGraphics, x, y, r int, style Style)

GenericCircle approximates a circle of radius r around (x,y) with lines.

func GenericKey

func GenericKey(bg BasicGraphics, x, y int, key Key, options PlotOptions)

GenericKey draws the key onto bg at (x,y).

func GenericPath

func GenericPath(mg MinimalGraphics, x, y []int, style Style)

GenericPath is the incomplete implementation of a list of points connected by straight lines. Incomplete: Dashed lines won't work properly.

func GenericRect

func GenericRect(mg MinimalGraphics, x, y, w, h int, style Style)

GenericRect draws a rectangle of size w x h at (x,y). Drawing is done by simple lines only.

func GenericRings

func GenericRings(bg BasicGraphics, wedges []Wedgeinfo, x, y, ro, ri int, eccentricity float64)

GeenricRings draws wedges for pie/ring charts charts. The pie's/ring's center is at (x,y) with ri and ro the inner and outer diameter. Eccentricity allows to correct for non-square pixels (e.g. in text mode).

func GenericScatter

func GenericScatter(bg BasicGraphics, points []EPoint, plotstyle PlotStyle, style Style)

GenericScatter draws the given points according to style. style.FillColor is used as color of error bars and style.FontSize is used as the length of the endmarks of the error bars. Both have suitable defaults if the FontXyz are not set. Point coordinates and errors must be provided in screen coordinates.

func GenericSymbol

func GenericSymbol(bg BasicGraphics, x, y int, style Style)

GenericSymbol draws the symbol defined by style at (x,y).

func GenericTextLen

func GenericTextLen(mg MinimalGraphics, t string, font Font) (width int)

GenericTextLen tries to determine the width in pixel of t if rendered into mg in using font.

func GenericWedge

func GenericWedge(mg MinimalGraphics, x, y, ro, ri int, phi, psi, ecc float64, style Style)

GenericWedge draws a pie/wedge just by lines

func GenericXAxis

func GenericXAxis(bg BasicGraphics, rng Range, y, ym int, options PlotOptions)

GenericXAxis draws the x-axis with range rng solely by graphic primitives of bg. The x-axis is drawn at y on the screen and the mirrored x-axis is drawn at ym.

func GenericYAxis

func GenericYAxis(bg BasicGraphics, rng Range, x, xm int, options PlotOptions)

GenericYAxis draws the y-axis with the range rng solely by graphic primitives of bg. The y.axis and the mirrord y-axis are drawn at x and ym respectively.

func IntegerValue

func IntegerValue(value, sum float64) (s string)

IntegerValue will format value (ignoring sum) as an integer. It is a convenience function which can be assigned to the PieChart.FmtVal or PieChart.FmtKey field.

func NextSymbol

func NextSymbol(s int) int

NextSymbol returns the next symbol of s: Either in the global list Symbol or (if not found there) the next character.

func PercentValue

func PercentValue(value, sum float64) (s string)

PercentValue formats value as percentage of sum. It is a convenience function which can be assigned to the PieChart.FmtVal or PieChart.FmtKey field.

func PercentilInt

func PercentilInt(data []int, p int) int

Return p percentil of pre-sorted integer data. 0 <= p <= 100.

func SanitizeRect

func SanitizeRect(x, y, w, h, r int) (int, int, int, int)

SanitizeRect returns the top left corner and the positive width and height of the given (possibly unsanitized) rectangle taking into account the line width r.

func SixvalFloat64

func SixvalFloat64(data []float64, p int) (min, lq, med, avg, uq, max float64)

Compute minimum, p percentil, median, average, 100-p percentil and maximum of values in data.

func SixvalInt

func SixvalInt(data []int, p int) (min, lq, med, avg, uq, max int)

Compute minimum, p percentil, median, average, 100-p percentil and maximum of values in data.

func SymbolIndex

func SymbolIndex(s int) (idx int)

SymbolIndex returns the index of the symbol s in Symbol or -1 if not found.

Types

type BarChart

type BarChart struct {
	XRange, YRange Range
	Title          string // Title of the chart
	Key            Key    // Key/Legend
	Horizontal     bool   // Display as horizontal bars (unimplemented)
	Stacked        bool   // Display different data sets ontop of each other (default is side by side)
	ShowVal        int    // Display values: 0: don't show; 1: above bar, 2: centerd in bar; 3: at top of bar
	ShowValFormat  func(float64) string
	SameBarWidth   bool        // all data sets use the same (smalest of all data sets) bar width
	BarWidthFac    float64     // if nonzero: scale determined bar width with this factor
	Options        PlotOptions // visual apperance, nil to use DefaultOptions
	Data           []BarChartData
}

BarChart draws simple bar charts. (Use CategoricalBarChart if your x axis is categorical, that is not numeric.)

Stacking is on a "both bars have _identical_ x values" basis.

func (*BarChart) AddData

func (c *BarChart) AddData(name string, data []Point, style Style)

AddData adds the data to the chart.

func (*BarChart) AddDataPair

func (c *BarChart) AddDataPair(name string, x, y []float64, style Style)

AddDataPair is a convenience method to add all the (x[i],y[i]) pairs to the chart.

func (*BarChart) Plot

func (c *BarChart) Plot(g Graphics)

Plot renders the chart to the graphics output g.

func (*BarChart) Reset

func (c *BarChart) Reset()

Reset chart to state before plotting.

type BarChartData

type BarChartData struct {
	Name    string
	Style   Style
	Samples []Point
}

BarChartData encapsulates data sets in a bar chart.

type Barinfo

type Barinfo struct {
	// contains filtered or unexported fields
}

Barinfo describes a rectangular bar (e.g. in a histogram or a bar plot).

type BasicGraphics

type BasicGraphics interface {
	MinimalGraphics
	Symbol(x, y int, style Style)                          // Put symbol s at (x,y)
	Rect(x, y, w, h int, style Style)                      // Draw (w x h) rectangle at (x,y)
	Wedge(x, y, ro, ri int, phi, psi float64, style Style) // Wedge
	Path(x, y []int, style Style)                          // Path of straight lines
	Options() PlotOptions                                  // access to current PlotOptions
}

BasicGraphics is an interface of the most basic graphic primitives. Any type which implements BasicGraphics can use generic implementations of the Graphics methods.

type Box

type Box struct {
	X           float64   // x-position of the box
	Avg         float64   // "average" value (uncommon in std. box plots, but sometimes useful)
	Q1, Med, Q3 float64   // lower quartil, median and upper quartil
	Low, High   float64   // low and hig end of whiskers (normaly last point in the 1.5*IQR range of Q1/3)
	Outliers    []float64 // list of y-values of outliers
}

Box represents a box in an boxplot.

func (Box) XErr

func (p Box) XErr() float64

func (Box) XVal

func (p Box) XVal() float64

func (Box) YErr

func (p Box) YErr() float64

func (Box) YVal

func (p Box) YVal() float64

type BoxChart

type BoxChart struct {
	XRange, YRange Range  // x and y axis
	Title          string // Title of the chart
	Key            Key    // Key/legend
	Options        PlotOptions
	Data           []BoxChartData // the data sets to draw
}

BoxChart represents box charts.

To faciliate standard use of box plots, the method AddSet() exists which will calculate the various elents of a box (e.g. med, q3, outliers, ...) from raw data.

func (*BoxChart) AddData

func (c *BoxChart) AddData(name string, data []Box, style Style)

AddData adds all boxes in data to the chart.

func (*BoxChart) AddSet

func (c *BoxChart) AddSet(x float64, data []float64, outlier bool)

AddSet will add to last data set in the chart one new box calculated from data. If outlier is true, than outliers (1.5*IQR from 25/75 percentil) are drawn. If outlier is false, than the wiskers extend from min to max.

func (*BoxChart) NextDataSet

func (c *BoxChart) NextDataSet(name string, style Style)

NextDataSet adds a new (empty) data set to chart. After adding the data set you can fill this last data set with AddSet()

func (*BoxChart) Plot

func (c *BoxChart) Plot(g Graphics)

Plot renders the chart to the graphic output g.

func (*BoxChart) Reset

func (c *BoxChart) Reset()

Reset chart to state before plotting.

type BoxChartData

type BoxChartData struct {
	Name    string
	Style   Style
	Samples []Box
}

BoxChartData encapsulates a data set in a box chart

type CatValue

type CatValue struct {
	Cat  string
	Val  float64
	Flag bool
}

CatValue is the standard implementation for CategoryValue.

func (CatValue) Category

func (c CatValue) Category() string

func (CatValue) Flaged

func (c CatValue) Flaged() bool

func (CatValue) Value

func (c CatValue) Value() float64

type CategoryChartData

type CategoryChartData struct {
	Name    string
	Style   []Style
	Samples []CatValue
}

type CategoryValue

type CategoryValue interface {
	Category() string
	Value() float64
	Flaged() bool
}

CategoryValue is the interface for any type of data which is a category-real-pair.

type Chart

type Chart interface {
	Plot(g Graphics) // Plot the chart to g.
	Reset()          // Reset any setting made during last plot.
}

Chart ist the very simple interface for all charts: They can be plotted to a graphics output.

type EPoint

type EPoint struct {
	X, Y           float64
	DeltaX, DeltaY float64 // Full range of x and y error, NaN for no errorbar.
	OffX, OffY     float64 // Offset of error range (must be < Delta)
}

EPoint represents a point in two dimensions (X,Y) with possible error ranges in both dimensions. To faciliate common symetric errors, OffX/Y defaults to 0 and only DeltaX/Y needs to be set up.

func (EPoint) BoundingBox

func (p EPoint) BoundingBox() (xl, yl, xh, yh float64)

func (EPoint) XErr

func (p EPoint) XErr() (float64, float64)

func (EPoint) XVal

func (p EPoint) XVal() float64

func (EPoint) YErr

func (p EPoint) YErr() (float64, float64)

func (EPoint) YVal

func (p EPoint) YVal() float64

type Expansion

type Expansion int

Expansion determines the way an axis range is expanded to align nicely with the tics on the axis.

const (
	ExpandNextTic Expansion = iota // Set min/max to next tic really below/above min/max of data.
	ExpandToTic                    // Set to next tic below/above or equal to min/max of data.
	ExpandTight                    // Use data min/max as limit.
	ExpandABit                     // Like ExpandToTic and add/subtract ExpandABitFraction of tic distance.
)

Suitable values for Expand in RangeMode.

type Font

type Font struct {
	Name  string      // "": default
	Size  FontSize    // relative size of font to default in output graphics
	Color color.Color // "": default, other: use this
}

Font describes a font.

type FontSize

type FontSize int

FontSize is the relative font size used in chart. Five sizes seem enough.

const (
	TinyFontSize FontSize = iota - 2
	SmallFontSize
	NormalFontSize
	LargeFontSize
	HugeFontSize
)

type Graphics

type Graphics interface {
	BasicGraphics

	Dimensions() (int, int) // character-width / height

	Begin() // start of chart drawing
	End()   // Done, cleanup

	// All stuff is preprocessed: sanitized, clipped, strings formated, integer coords,
	// screen coordinates,
	XAxis(xr Range, ys, yms int, options PlotOptions) // Draw x axis xr at screen position ys (and yms if mirrored)
	YAxis(yr Range, xs, xms int, options PlotOptions) // Same for y axis.

	Scatter(points []EPoint, plotstyle PlotStyle, style Style) // Points, Lines and Line+Points
	Boxes(boxes []Box, width int, style Style)                 // Boxplots
	Bars(bars []Barinfo, style Style)                          // any type of histogram/bars
	Rings(wedeges []Wedgeinfo, x, y, ro, ri int)               // Pie/ring diagram elements

	Key(x, y int, key Key, options PlotOptions) // place key at x,y
}

Graphics is the interface all chart drivers have to implement

type GridMode

type GridMode int

GridMode describes the way a grid on the major tics is drawn

const (
	GridOff    GridMode = iota // No grid lines
	GridLines                  // Grid lines
	GridBlocks                 // Zebra style background
)

type HistChart

type HistChart struct {
	XRange, YRange Range       // Lower limit of YRange is fixed to 0 and not available for input
	Title          string      // Title of chart
	Key            Key         // Key/Legend
	Counts         bool        // Display counts instead of frequencies
	Stacked        bool        // Display different data sets ontop of each other
	Shifted        bool        // Shift non-stacked bars sideways (and make them smaler)
	FirstBin       float64     // center of the first (lowest bin)
	BinWidth       float64     // Width of bins (0: auto)
	Gap            float64     // gap between bins in (bin-width units): 0<=Gap<1,
	Sep            float64     // separation of bars in one bin (in bar width units) -1<Sep<1
	Kernel         Kernel      // Smoothing kernel (usable only for non-stacked histograms)
	Options        PlotOptions // general stylistic optins
	Data           []HistChartData
}

HistChart represents histogram charts.

Histograms should not be mixed up with bar charts produced by BarChart: Histograms are computed (binified) automatically from the raw data.

func (*HistChart) AddData

func (c *HistChart) AddData(name string, data []float64, style Style)

AddData will add data to the plot. Legend will be updated by name.

func (*HistChart) AddDataGeneric

func (c *HistChart) AddDataGeneric(name string, data []Value, style Style)

AddDataGeneric is the generic version which allows the addition of any type implementing the Value interface.

func (*HistChart) AddDataInt

func (c *HistChart) AddDataInt(name string, data []int, style Style)

AddDataInt is a convenience method to add integer data (a simple wrapper around AddData).

func (*HistChart) Plot

func (c *HistChart) Plot(g Graphics)

Plot will output the chart to the graphic device g.

func (*HistChart) Reset

func (c *HistChart) Reset()

Reset chart to state before plotting.

type HistChartData

type HistChartData struct {
	Name    string
	Style   Style
	Samples []float64
}

HistChartData encapsulates one data set in a histogram chart.

type Kernel

type Kernel func(x float64) float64

Kernel is a smoothing kernel for histograms.

var (
	// 1/2
	RectangularKernel = func(x float64) float64 {
		if x >= -1 && x < 1 {
			return 0.5
		}
		return 0
	}

	// 1 - |x|
	TriangularKernel = func(x float64) float64 {
		if x >= -1 && x < 1 {
			return 1 - math.Abs(x)
		}
		return 0
	}

	// 15/16 * (1-x^2)^2
	BisquareKernel Kernel = func(x float64) float64 {
		if x >= -1 && x < 1 {
			a := (1 - x*x)
			return 15.0 / 16.0 * a * a
		}
		return 0
	}

	// 35/32 * (1-x^2)^3
	TriweightKernel Kernel = func(x float64) float64 {
		if x >= -1 && x < 1 {
			a := (1 - x*x)
			return 35.0 / 32.0 * a * a * a
		}
		return 0
	}

	// 3/4 * (1-x^2)
	EpanechnikovKernel Kernel = func(x float64) float64 {
		if x >= -1 && x < 1 {
			return 3.0 / 4.0 * (1.0 - x*x)
		}
		return 0
	}

	// 1/sqrt(2pi) * exp(-1/2x^2)
	GaussKernel Kernel = func(x float64) float64 {
		return sqrt2piinv * math.Exp(-0.5*x*x)
	}
)

Some common smoothing kernels. All are identical 0 outside [-1,1[.

type Key

type Key struct {
	Hide    bool       // Don't show key/legend if true
	Cols    int        // Number of colums to use. If <0 fill rows before colums
	Border  int        // -1: off, 0: std, 1...:other styles
	Pos     string     // default "" is "itr"
	Entries []KeyEntry // List of entries in the legend
	X, Y    int
}

Key encapsulates settings for keys/legends in a chart.

Key placement is governed by Pos which may take the following values:

     otl  otc  otr
    +-------------+          o: outside
olt |itl  itc  itr| ort      i: inside
    |             |          t: top
olc |icl  icc  icr| orc      c: centered
    |             |          b: bottom
olb |ibl  ibc  ibr| orb      l: left
    +-------------+          c: centered
     obl  obc  obr           r: right

func (Key) Layout

func (key Key) Layout(bg BasicGraphics, m [][]*KeyEntry, font Font) (w, h int, colwidth, rowheight []int)

Layout determines how wide and broad the places keys in m will be rendered.

func (Key) Place

func (key Key) Place() (matrix [][]*KeyEntry)

Place layouts the Entries in key in the requested (by key.Cols) matrix format

type KeyEntry

type KeyEntry struct {
	Text      string    // Text to display
	PlotStyle PlotStyle // What to show: symbol, line, bar or combination thereof
	Style     Style     // How to show

}

KeyEntry encapsulates an antry in the key/legend.

type LayoutData

type LayoutData struct {
	Width, Height      int // width and height of graph area
	Left, Top          int // left and top margin
	KeyX, KeyY         int // x and y coordiante of key
	NumXtics, NumYtics int // suggested numer of tics for both axis
}

LayoutData encapsulates the layout of the graph area in the whole drawing area.

type LineStyle

type LineStyle int

LineStyle describes the different types of lines.

const (
	SolidLine      LineStyle = iota //  ----------------------
	DashedLine                      //  ----  ----  ----  ----
	DottedLine                      //  - - - - - - - - - - -
	DashDotDotLine                  //  ----  -  -  ----  -  -
	LongDashLine                    //
	LongDotLine
)

The supported line styles.

type MinimalGraphics

type MinimalGraphics interface {
	Background() (r, g, b, a uint8)                         // Color of background
	FontMetrics(font Font) (fw float32, fh int, mono bool)  // Return fontwidth and -height in pixel
	TextLen(t string, font Font) int                        // Length=width of t in screen units if set on font
	Line(x0, y0, x1, y1 int, style Style)                   // Draw line from (x0,y0) to (x1,y1)
	Text(x, y int, t string, align string, rot int, f Font) // Put t at (x,y) rotated by rot aligned [[tcb]][lcr]
}

MinimalGraphics is the interface any graphics driver must implement, so that he can fall back to the generic routines for the higher level outputs.

type MirrorAxis

type MirrorAxis int

MirrorAxis describes if and how an axis is drawn on the oposite side of a chart,

const (
	MirrorAxisAndTics MirrorAxis = 0  // draw a full mirrored axis including tics
	MirrorNothing     MirrorAxis = -1 // do not draw a mirrored axis
	MirrorAxisOnly    MirrorAxis = 1  // just draw a mirrord axis, but omit tics
)

type PieChart

type PieChart struct {
	Title   string  // The title
	Key     Key     // The Key/Legend
	Inner   float64 // relative radius of inner white are (set to 0.7 to produce ring chart)
	Options PlotOptions
	Data    []CategoryChartData // The data

	FmtVal func(value, sume float64) string // add value labels to pie segments
	FmtKey func(value, sume float64) string // add value labels to key entries
}

PieChart represents pie and ring charts. Data is exported but it you should use the AddData, AddDataPair and AddIntDataPair methods to populate this field. The FmtVal and FmtKey function are used to format optional labels on the pie segments (FmtVal) and on the legend/key entries if non nil. The FmtKey must be set before adding data via the AddXY methods.

func (*PieChart) AddData

func (c *PieChart) AddData(name string, data []CatValue, style []Style)

func (*PieChart) AddDataPair

func (c *PieChart) AddDataPair(name string, cat []string, val []float64)

func (*PieChart) AddIntDataPair

func (c *PieChart) AddIntDataPair(name string, cat []string, val []int)

func (*PieChart) Plot

func (c *PieChart) Plot(g Graphics)

Plot outputs the scatter chart sc to g.

func (*PieChart) Reset

func (c *PieChart) Reset()

Reset chart to state before plotting.

type PlotElement

type PlotElement int

PlotElement identifies one element in a plot/chart

const (
	MajorAxisElement PlotElement = iota
	MinorAxisElement
	MajorTicElement
	MinorTicElement
	ZeroAxisElement
	GridLineElement
	GridBlockElement
	KeyElement
	TitleElement
	RangeLimitElement
)

type PlotOptions

type PlotOptions map[PlotElement]Style

PlotOptions contains a Style for each PlotElement. If a PlotOption does not contain a certainPlotElement the value in DefaultStyle is used.

type PlotStyle

type PlotStyle int

PlotStyle describes how data and functions are drawn in scatter plots. Can be used to describe how a key entry is drawn

const (
	PlotStylePoints      PlotStyle = iota + 1 // draw symbol at data point
	PlotStyleLines                            // connect data points by straight lines
	PlotStyleLinesPoints                      // symbols and lines
	PlotStyleBox                              // produce boxplot
)

type Point

type Point struct{ X, Y float64 }

Point is a point in two dimensions (x,y) implementing XYValue.

func (Point) XErr

func (p Point) XErr() (float64, float64)

func (Point) XVal

func (p Point) XVal() float64

func (Point) YErr

func (p Point) YErr() (float64, float64)

func (Point) YVal

func (p Point) YVal() float64

type Range

type Range struct {
	Label            string     // Label of axis
	MinMode, MaxMode RangeMode  // How to handel min and max of this axis/range
	TicSetting       TicSetting // How to handle tics.
	DataMin, DataMax float64    // Actual min/max values from data. If both zero: not calculated
	ShowLimits       bool       // Display axis Min and Max values on plot
	ShowZero         bool       // Add line to show 0 of this axis
	Category         []string   // If not empty (and neither Log nor Time): Use Category[n] as tic label at pos n+1.

	// The following values are set up during plotting
	Min, Max float64 // Actual minium and maximum of this axis/range.
	Tics     []Tic   // List of tics to display

	// The following functions are set up during plotting
	Norm        func(float64) float64 // Function to map [Min:Max] to [0:1]
	InvNorm     func(float64) float64 // Inverse of Norm()
	Data2Screen func(float64) int     // Function to map data value to screen position
	Screen2Data func(int) float64     // Inverse of Data2Screen
}

Range encapsulates all information about an axis.

func (*Range) Fixed

func (r *Range) Fixed(min, max, delta float64)

Fixed is a helper (just reduces typing) functions which turns of autoscaling and sets the axis range to [min,max] and the tic distance to delta.

func (*Range) Init

func (r *Range) Init()

func (*Range) Reset

func (r *Range) Reset()

Reset the fields in r which have been set up during a plot.

func (*Range) Setup

func (r *Range) Setup(desiredNumberOfTics, maxNumberOfTics, sWidth, sOffset int, revert bool)

Setup several fields of the Range r according to RangeModes and TicSettings. DataMin and DataMax of r must be present and should indicate lowest and highest value present in the data set. The following fields of r are filled:

(T)Min and (T)Max    lower and upper limit of axis, (T)-version for date/time axis
Tics                 slice of tics to draw
TicSetting.(T)Delta  actual tic delta
Norm and InvNorm     mapping of [lower,upper]_data --> [0:1] and inverse
Data2Screen          mapping of data to screen coordinates
Screen2Data          inverse of Data2Screen

The parameters desiredNumberOfTics and maxNumberOfTics are what the say. sWidth and sOffset are screen-width and -offset and are used to set up the Data-Screen conversion functions. If revert is true, than screen coordinates are assumed to be the other way around than mathematical coordinates.

TODO(vodo) seperate screen stuff into own method.

type RangeMode

type RangeMode struct {
	Fixed        bool      // If false: autoscaling. If true: use (T)Value/TValue as fixed setting
	Constrained  bool      // If false: full autoscaling. If true: use (T)Lower (T)Upper as limits
	Expand       Expansion // One of ExpandNextTic, ExpandTight, ExpandABit
	Value        float64   // Value of end point of axis in Fixed=true mode, ignorder otherwise
	Lower, Upper float64   // Lower and upper limit for constrained autoscaling
}

RangeMode describes how one end of an axis is set up. There are basically three different main modes:

  • Fixed: Fixed==true. Use Value/TValue as fixed value this ignoring the actual data range.
  • Unconstrained autoscaling: Fixed==false && Constrained==false. Set range to whatever data requires.
  • Constrained autoscaling: Fixed==false && Constrained==true. Scale axis according to data present, but limit scaling to intervall [Lower,Upper]

For both autoscaling modes Expand defines how much expansion is done below/above the lowest/highest data point.

type Real

type Real float64

Real is a float64 implementing the Value interface.

func (Real) XVal

func (r Real) XVal() float64

type ScatterChart

type ScatterChart struct {
	XRange, YRange Range  // X and Y axis
	Title          string // Title of the chart
	Key            Key    // Key/Legend
	Options        PlotOptions
	Data           []ScatterChartData // The actual data (filled with Add...-methods)
	NSamples       int                // number of samples for function plots
}

ScatterChart represents scatter charts, line charts and function plots.

func (*ScatterChart) AddData

func (c *ScatterChart) AddData(name string, data []EPoint, plotstyle PlotStyle, style Style)

AddData adds points in data to chart. A key/legend entry is produced if name is not empty.

func (*ScatterChart) AddDataGeneric

func (c *ScatterChart) AddDataGeneric(name string, data []XYErrValue, plotstyle PlotStyle, style Style)

AddDataGeneric is the generiv version of AddData which allows any type to be plotted that implements the XYErrValue interface.

func (*ScatterChart) AddDataPair

func (c *ScatterChart) AddDataPair(name string, x, y []float64, plotstyle PlotStyle, style Style)

AddDataPair is a convenience method which wrapps around AddData: It adds the points (x[n],y[n]) to the chart.

func (*ScatterChart) AddFunc

func (c *ScatterChart) AddFunc(name string, f func(float64) float64, plotstyle PlotStyle, style Style)

AddFunc adds a function f to this chart. A key/legend entry is produced if name is not empty.

func (*ScatterChart) Plot

func (c *ScatterChart) Plot(g Graphics)

Plot outputs the scatter chart to the graphic output g.

func (*ScatterChart) Reset

func (c *ScatterChart) Reset()

Reset chart to state before plotting.

type ScatterChartData

type ScatterChartData struct {
	Name      string                // The name of this data set. TODO: unused?
	PlotStyle PlotStyle             // Points, Lines+Points or Lines only
	Style     Style                 // Color, sizes, pointtype, linestyle, ...
	Samples   []EPoint              // The actual points for scatter/lines charts
	Func      func(float64) float64 // The function to draw.
}

ScatterChartData encapsulates a data set or function in a scatter chart. Not both Samples and Func may be non nil at the same time.

type StripChart

type StripChart struct {
	Jitter       bool // Add jitter to help distinguish overlapping values
	ScatterChart      // The embeded ScatterChart is responsible for all drawing
}

StripChart represents very simple strip charts.

func (*StripChart) AddData

func (sc *StripChart) AddData(name string, data []float64, style Style)

AddData adds data to the strip chart.

func (*StripChart) AddDataGeneric

func (sc *StripChart) AddDataGeneric(name string, data []Value)

func (*StripChart) Plot

func (sc *StripChart) Plot(g Graphics)

Plot outputs the strip chart sc to g.

func (*StripChart) Reset

func (sc *StripChart) Reset()

Reset chart to state before plotting.

type Style

type Style struct {
	Symbol      int         // 0: no symbol; any codepoint: this symbol
	SymbolColor color.Color // color of symbol
	SymbolSize  float64     // scaling factor of symbol
	LineStyle   LineStyle   // SolidLine, DashedLine, DottedLine, .... see below
	LineColor   color.Color // color of line
	LineWidth   int         // 0: no line,  >=1 width of line in pixel
	Font        Font        // the font to use
	FillColor   color.Color
}

Style contains all information about all graphic elements in a chart. All colors are in the form "#rrggbb" with rr/gg/bb hexvalues. Not all elements of a plot use all fields in this struct.

func AutoStyle

func AutoStyle(i int, fill bool) (style Style)

AutoStyle produces a styles based on StandardColors, StandardLineStyles, and StandardSymbols. Call with fill = true for charts with filled elements (hist, bar, cbar, pie).

func ElementStyle

func ElementStyle(options PlotOptions, element PlotElement) Style

type Tic

type Tic struct {
	Pos      float64 // position of the tic on the axis (in data coordinates).
	LabelPos float64 // position of the label on the axis (in data coordinates).
	Label    string  // the Label of the tic
	Align    int     // alignment of the label:  -1: left/top,  0 center,  1 right/bottom (unused)
}

Tic describs a single tic on an axis.

type TicSetting

type TicSetting struct {
	Hide       bool       // dont show tics if true
	HideLabels bool       // don't show tic labels if true
	Tics       int        // 0: across axis,  1: inside,  2: outside,  other: off
	Minor      int        // 0: off,  1: auto,  >1: number of intervalls (not number of tics!)
	Delta      float64    // wanted step between major tics.  0 means auto
	Grid       GridMode   // GridOff, GridLines, GridBlocks
	Mirror     MirrorAxis // 0: mirror axis and tics, -1: don't mirror anything, 1: mirror axis only (no tics)

	// Format is used to print the tic labels. If unset FmtFloat is used.
	Format func(float64) string

	UserDelta bool // true if Delta was input
}

TicSetting describes how (if at all) tics are shown on an axis.

type Value

type Value interface {
	XVal() float64
}

Value is the interface for any type of data representable by a real. Its standard implementation here is Real (float64).

type Wedgeinfo

type Wedgeinfo struct {
	Phi, Psi float64 // Start and ende of wedge. Fuill circle if |phi-psi| > 4pi
	Text, Tp string  // label text and text position: [ico]
	Style    Style   // style of this wedge
	Font     Font    // font of text
	Shift    int     // Highlighting of wedge
}

Wedgeinfo describes a wedge in a pie chart.

type XYErrValue

type XYErrValue interface {
	XVal() float64
	YVal() float64
	XErr() (float64, float64) // X-range [min,max], error intervall. Use NaN to indicate "no error".
	YErr() (float64, float64) // Y-range error interval (like XErr).
}

XYErrValue is the interface for any type of data which is point-like (x,y) and has some measurement error.

type XYValue

type XYValue interface {
	XVal() float64
	YVal() float64
}

XYValue is the interface for any type of data which is point-like and has a x- and y-coordinate. Its standard implementation here is Point.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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