chart

package module
v1.0.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2016 License: MIT Imports: 15 Imported by: 0

README

go-chart

Build Status

Package chart is a very simple golang native charting library that supports timeseries and continuous line charts.

The API is still in a bit of flux, so it is adviseable to wait until I tag a v1.0 release before using in a production capacity.

Installation

To install chart run the following:

> go get -u github.com/wcharczuk/go-chart

Most of the components are interchangeable so feel free to crib whatever you want.

Usage

The chart code to produce the above is as follows:

// note this assumes that xvalues and yvalues
// have been pulled from a pricing service.
graph := chart.Chart{
    Width:  1024,
    Height: 400,
    YAxis: chart.YAxis {
        Style: chart.Style{
            Show: true,
        },
    },
    XAxis: chart.XAxis {
        Style: chart.Style{
            Show: true,
        },
    },
    Series: []chart.Series{
        chart.TimeSeries{
            XValues: xvalues,
            YValues: yvalues,
            Style: chart.Style {
                FillColor: chart.DefaultSeriesStrokeColors[0].WithAlpha(64),
            },
        },
        chart.AnnotationSeries{
            Name: "Last Value",
            Style: chart.Style{
                Show:        true,
                StrokeColor: chart.DefaultSeriesStrokeColors[0],
            },
            Annotations: []chart.Annotation{
                chart.Annotation{
                    X:     chart.TimeToFloat64(xvalues[len(xvalues)-1]),
                    Y:     yvalues[len(yvalues)-1],
                    Label: chart.FloatValueFormatter(yvalues[len(yvalues)-1]),
                },
            },
        },
    },
}
graph.Render(chart.PNG, buffer) //thats it!

The key areas to note are that we have to explicitly turn on two features, the axes and add the last value label annotation series. When calling .Render(..) we add a parameter, chart.PNG that tells the renderer to use a raster renderer. Another option is to use chart.SVG which will use the vector renderer and create an svg representation of the chart.

Alternate Usage

You can alternately leave a bunch of features turned off and constrain the proportions to something like a spark line:

The code to produce the above would be:

// note this assumes that xvalues and yvalues
// have been pulled from a pricing service.
graph := chart.Chart{
    Width:  1024,
    Height: 100,
    Series: []chart.Series{
        chart.TimeSeries{
            XValues: xvalues,
            YValues: yvalues,
        },
    },
}
graph.Render(chart.PNG, buffer)

2 Y-Axis Charts

It is also possible to draw series against 2 separate y-axis with their own ranges (usually good for comparison charts). In order to map the series to an alternate axis make sure to set the YAxis property of the series to YAxisSecondary.

graph := chart.Chart{
    Title: stock.Name,
    TitleStyle: chart.Style{
        Show: false,
    },
    Width:  width,
    Height: height,
    XAxis: chart.XAxis{
        Style: chart.Style{
            Show: true,
        },
    },
    YAxis: chart.YAxis{
        Style: chart.Style{
            Show: true,
        },
    },
    Series: []chart.Series{
        chart.TimeSeries{
            Name:    "vea",
            XValues: vx,
            YValues: vy,
            Style: chart.Style{
                Show: true,
                StrokeColor: chart.GetDefaultSeriesStrokeColor(0),
                FillColor:   chart.GetDefaultSeriesStrokeColor(0).WithAlpha(64),
            },
        },
        chart.TimeSeries{
            Name:    "spy",
            XValues: cx,
            YValues: cy,
            YAxis:   chart.YAxisSecondary,  // key (!)
            Style: chart.Style{
                Show: true,
                StrokeColor: chart.GetDefaultSeriesStrokeColor(1),
                FillColor:   chart.GetDefaultSeriesStrokeColor(1).WithAlpha(64),
            },
        },
        chart.AnnotationSeries{
            Name: fmt.Sprintf("%s - Last Value", "vea"),
            Style: chart.Style{
                Show:        true,
                StrokeColor: chart.GetDefaultSeriesStrokeColor(0),
            },
            Annotations: []chart.Annotation{
                chart.Annotation{
                    X:     float64(vx[len(vx)-1].Unix()),
                    Y:     vy[len(vy)-1],
                    Label: fmt.Sprintf("%s - %s", "vea", chart.FloatValueFormatter(vy[len(vy)-1])),
                },
            },
        },
        chart.AnnotationSeries{
            Name: fmt.Sprintf("%s - Last Value", "goog"),
            Style: chart.Style{
                Show:        true,
                StrokeColor: chart.GetDefaultSeriesStrokeColor(1),
            },
            YAxis: chart.YAxisSecondary, // key (!)
            Annotations: []chart.Annotation{
                chart.Annotation{
                    X:     float64(cx[len(cx)-1].Unix()),
                    Y:     cy[len(cy)-1],
                    Label: fmt.Sprintf("%s - %s", "goog", chart.FloatValueFormatter(cy[len(cy)-1])),
                },
            },
        },
    },
}
graph.Render(chart.PNG, buffer)

Moving Averages

You can now also graph a moving average of a series using a special MovingAverageSeries that takes an InnerSeries as a required argument.

There is a helper method, GetLastValue on the MovingAverageSeries to aid in creating a last value annotation for the series.

Design Philosophy

I wanted to make a charting library that used only native golang, that could be stood up on a server (i.e. it had built in fonts).

The goal with the API itself is to have the "zero value be useful", and to require the user to not code more than they absolutely needed.

Contributions

This library is super early but contributions are welcome.

Documentation

Index

Constants

View Source
const (
	// DefaultChartHeight is the default chart height.
	DefaultChartHeight = 400
	// DefaultChartWidth is the default chart width.
	DefaultChartWidth = 200
	// DefaultStrokeWidth is the default chart line/stroke width.
	DefaultStrokeWidth = 1.0
	// DefaultAxisLineWidth is the line width of the axis lines.
	DefaultAxisLineWidth = 1.0
	//DefaultDPI is the default dots per inch for the chart.
	DefaultDPI = 92.0
	// DefaultMinimumFontSize is the default minimum font size.
	DefaultMinimumFontSize = 8.0
	// DefaultFontSize is the default font size.
	DefaultFontSize = 10.0
	// DefaultTitleFontSize is the default title font size.
	DefaultTitleFontSize = 18.0
	// DefaultAnnotationDeltaWidth is the width of the left triangle out of annotations.
	DefaultAnnotationDeltaWidth = 10
	// DefaultAnnotationFontSize is the font size of annotations.
	DefaultAnnotationFontSize = 10.0
	// DefaultAxisFontSize is the font size of the axis labels.
	DefaultAxisFontSize = 10.0
	// DefaultTitleTop is the default distance from the top of the chart to put the title.
	DefaultTitleTop = 10

	// DefaultYAxisMargin is the default distance from the right of the canvas to the y axis labels.
	DefaultYAxisMargin = 10
	// DefaultXAxisMargin is the default distance from bottom of the canvas to the x axis labels.
	DefaultXAxisMargin = 10

	//DefaultVerticalTickHeight is half the margin.
	DefaultVerticalTickHeight = DefaultXAxisMargin >> 1
	//DefaultHorizontalTickWidth is half the margin.
	DefaultHorizontalTickWidth = DefaultYAxisMargin >> 1

	// DefaultTickCount is the default number of ticks to show
	DefaultTickCount = 10
	// DefaultTickCountSanityCheck is a hard limit on number of ticks to prevent infinite loops.
	DefaultTickCountSanityCheck = 1 << 10 //1024

	// DefaultMinimumTickHorizontalSpacing is the minimum distance between horizontal ticks.
	DefaultMinimumTickHorizontalSpacing = 20
	// DefaultMinimumTickVerticalSpacing is the minimum distance between vertical ticks.
	DefaultMinimumTickVerticalSpacing = 20

	// DefaultDateFormat is the default date format.
	DefaultDateFormat = "2006-01-02"
	// DefaultDateHourFormat is the date format for hour timestamp formats.
	DefaultDateHourFormat = "01-02 3PM"
	// DefaultFloatFormat is the default float format.
	DefaultFloatFormat = "%.2f"
	// DefaultPercentValueFormat is the default percent format.
	DefaultPercentValueFormat = "%0.2f%%"
)
View Source
const (
	// DefaultMovingAverageWindowSize is the default number of values to average.
	DefaultMovingAverageWindowSize = 5
)

Variables

View Source
var (
	// DefaultBackgroundColor is the default chart background color.
	// It is equivalent to css color:white.
	DefaultBackgroundColor = drawing.Color{R: 255, G: 255, B: 255, A: 255}
	// DefaultBackgroundStrokeColor is the default chart border color.
	// It is equivalent to color:white.
	DefaultBackgroundStrokeColor = drawing.Color{R: 255, G: 255, B: 255, A: 255}
	// DefaultCanvasColor is the default chart canvas color.
	// It is equivalent to css color:white.
	DefaultCanvasColor = drawing.Color{R: 255, G: 255, B: 255, A: 255}
	// DefaultCanvasStrokeColor is the default chart canvas stroke color.
	// It is equivalent to css color:white.
	DefaultCanvasStrokeColor = drawing.Color{R: 255, G: 255, B: 255, A: 255}
	// DefaultTextColor is the default chart text color.
	// It is equivalent to #333333.
	DefaultTextColor = drawing.Color{R: 51, G: 51, B: 51, A: 255}
	// DefaultAxisColor is the default chart axis line color.
	// It is equivalent to #333333.
	DefaultAxisColor = drawing.Color{R: 51, G: 51, B: 51, A: 255}
	// DefaultStrokeColor is the default chart border color.
	// It is equivalent to #efefef.
	DefaultStrokeColor = drawing.Color{R: 239, G: 239, B: 239, A: 255}
	// DefaultFillColor is the default fill color.
	// It is equivalent to #0074d9.
	DefaultFillColor = drawing.Color{R: 0, G: 217, B: 116, A: 255}
	// DefaultAnnotationFillColor is the default annotation background color.
	DefaultAnnotationFillColor = drawing.Color{R: 255, G: 255, B: 255, A: 255}
	// DefaultGridLineColor is the default grid line color.
	DefaultGridLineColor = drawing.Color{R: 239, G: 239, B: 239, A: 255}
)
View Source
var (
	// DashArrayDots is a dash array that represents '....' style stroke dashes.
	DashArrayDots = []int{1, 1}
	// DashArrayDashesSmall is a dash array that represents '- - -' style stroke dashes.
	DashArrayDashesSmall = []int{3, 3}
	// DashArrayDashesMedium is a dash array that represents '-- -- --' style stroke dashes.
	DashArrayDashesMedium = []int{5, 5}
	// DashArrayDashesLarge is a dash array that represents '----- ----- -----' style stroke dashes.
	DashArrayDashesLarge = []int{10, 10}
)
View Source
var (
	// DefaultAnnotationPadding is the padding around an annotation.
	DefaultAnnotationPadding = Box{Top: 3, Left: 5, Right: 5, Bottom: 5}
	// DefaultBackgroundPadding is the default canvas padding config.
	DefaultBackgroundPadding = Box{Top: 5, Left: 5, Right: 5, Bottom: 5}
)
View Source
var (
	// DefaultSeriesStrokeColors are a couple default series colors.
	DefaultSeriesStrokeColors = []drawing.Color{
		drawing.Color{R: 0, G: 116, B: 217, A: 255},
		drawing.Color{R: 0, G: 217, B: 116, A: 255},
		drawing.Color{R: 217, G: 0, B: 116, A: 255},
	}
)

Functions

func AbsInt

func AbsInt(value int) int

AbsInt returns the absolute value of an integer.

func DrawAnnotation

func DrawAnnotation(r Renderer, canvasBox Box, s Style, lx, ly int, label string)

DrawAnnotation draws an anotation with a renderer.

func DrawBox

func DrawBox(r Renderer, b Box, s Style)

DrawBox draws a box with a given style.

func DrawLineSeries

func DrawLineSeries(r Renderer, canvasBox Box, xrange, yrange Range, s Style, vs ValueProvider)

DrawLineSeries draws a line series with a renderer.

func DrawText

func DrawText(r Renderer, text string, x, y int, s Style)

DrawText draws text with a given style.

func DrawTextCentered

func DrawTextCentered(r Renderer, text string, x, y int, s Style)

DrawTextCentered draws text with a given style centered.

func FloatValueFormatter

func FloatValueFormatter(v interface{}) string

FloatValueFormatter is a ValueFormatter for float64.

func FloatValueFormatterWithFormat

func FloatValueFormatterWithFormat(v interface{}, floatFormat string) string

FloatValueFormatterWithFormat is a ValueFormatter for float64 with a given format.

func GetDefaultFont

func GetDefaultFont() (*truetype.Font, error)

GetDefaultFont returns the default font (Roboto-Medium).

func GetDefaultSeriesStrokeColor

func GetDefaultSeriesStrokeColor(index int) drawing.Color

GetDefaultSeriesStrokeColor returns a color from the default list by index. NOTE: the index will wrap around (using a modulo).g

func GetRoundToForDelta

func GetRoundToForDelta(delta float64) float64

GetRoundToForDelta returns a `roundTo` value for a given delta.

func MaxInt

func MaxInt(values ...int) int

MaxInt returns the maximum of a set of integers.

func MinAndMax

func MinAndMax(values ...float64) (min float64, max float64)

MinAndMax returns both the min and max in one pass.

func MinAndMaxOfTime

func MinAndMaxOfTime(values ...time.Time) (min time.Time, max time.Time)

MinAndMaxOfTime returns the min and max of a given set of times in one pass.

func MinInt

func MinInt(values ...int) int

MinInt returns the minimum of a set of integers.

func PercentDifference

func PercentDifference(v1, v2 float64) float64

PercentDifference computes the percentage difference between two values. The formula is (v2-v1)/v1.

func PercentValueFormatter

func PercentValueFormatter(v interface{}) string

PercentValueFormatter is a formatter for percent values. NOTE: it normalizes the values, i.e. multiplies by 100.0.

func RoundDown

func RoundDown(value, roundTo float64) float64

RoundDown rounds down to a given roundTo value.

func RoundUp

func RoundUp(value, roundTo float64) float64

RoundUp rounds up to a given roundTo value.

func Seq

func Seq(start, end float64, steps ...float64) []float64

Seq produces an array of floats from [start,end] by optional steps.

func Slices

func Slices(count int, total float64) []float64

Slices generates N slices that span the total. The resulting array will be intermediate indexes until total.

func TimeHourValueFormatter

func TimeHourValueFormatter(v interface{}) string

TimeHourValueFormatter is a ValueFormatter for timestamps.

func TimeToFloat64

func TimeToFloat64(t time.Time) float64

TimeToFloat64 returns a float64 representation of a time.

func TimeValueFormatter

func TimeValueFormatter(v interface{}) string

TimeValueFormatter is a ValueFormatter for timestamps.

func TimeValueFormatterWithFormat

func TimeValueFormatterWithFormat(v interface{}, dateFormat string) string

TimeValueFormatterWithFormat is a ValueFormatter for timestamps with a given format.

Types

type Annotation

type Annotation struct {
	X, Y  float64
	Label string
}

Annotation is a label on the chart.

type AnnotationSeries

type AnnotationSeries struct {
	Name        string
	Style       Style
	YAxis       YAxisType
	Annotations []Annotation
}

AnnotationSeries is a series of labels on the chart.

func (AnnotationSeries) GetName

func (as AnnotationSeries) GetName() string

GetName returns the name of the time series.

func (AnnotationSeries) GetStyle

func (as AnnotationSeries) GetStyle() Style

GetStyle returns the line style.

func (AnnotationSeries) GetYAxis

func (as AnnotationSeries) GetYAxis() YAxisType

GetYAxis returns which YAxis the series draws on.

func (AnnotationSeries) Measure

func (as AnnotationSeries) Measure(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) Box

Measure returns a bounds box of the series.

func (AnnotationSeries) Render

func (as AnnotationSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style)

Render draws the series.

type Axis

type Axis interface {
	GetName() string
	GetStyle() Style
	GetTicks(r Renderer, ra Range, vf ValueFormatter) []Tick
	GetGridLines(ticks []Tick) []GridLine
	Render(c *Chart, r Renderer, canvasBox Box, ra Range, ticks []Tick)
}

Axis is a chart feature detailing what values happen where.

type Box

type Box struct {
	Top    int
	Left   int
	Right  int
	Bottom int
}

Box represents the main 4 dimensions of a box.

func MeasureAnnotation

func MeasureAnnotation(r Renderer, canvasBox Box, s Style, lx, ly int, label string) Box

MeasureAnnotation measures how big an annotation would be.

func (Box) Aspect

func (b Box) Aspect() float64

Aspect returns the aspect ratio of the box.

func (Box) Center

func (b Box) Center() (x, y int)

Center returns the center of the box

func (Box) Clone

func (b Box) Clone() Box

Clone returns a new copy of the box.

func (Box) Constrain

func (b Box) Constrain(other Box) Box

Constrain is similar to `Fit` except that it will work more literally like the opposite of grow.

func (Box) Equals

func (b Box) Equals(other Box) bool

Equals returns if the box equals another box.

func (Box) Fit

func (b Box) Fit(other Box) Box

Fit is functionally the inverse of grow. Fit maintains the original aspect ratio of the `other` box, but constrains it to the bounds of the target box.

func (Box) GetBottom

func (b Box) GetBottom(defaults ...int) int

GetBottom returns a coalesced value with a default.

func (Box) GetLeft

func (b Box) GetLeft(defaults ...int) int

GetLeft returns a coalesced value with a default.

func (Box) GetRight

func (b Box) GetRight(defaults ...int) int

GetRight returns a coalesced value with a default.

func (Box) GetTop

func (b Box) GetTop(defaults ...int) int

GetTop returns a coalesced value with a default.

func (Box) Grow

func (b Box) Grow(other Box) Box

Grow grows a box based on another box.

func (Box) Height

func (b Box) Height() int

Height returns the height

func (Box) IsBiggerThan

func (b Box) IsBiggerThan(other Box) bool

IsBiggerThan returns if a box is bigger than another box.

func (Box) IsSmallerThan

func (b Box) IsSmallerThan(other Box) bool

IsSmallerThan returns if a box is smaller than another box.

func (Box) IsZero

func (b Box) IsZero() bool

IsZero returns if the box is set or not.

func (Box) OuterConstrain

func (b Box) OuterConstrain(bounds, other Box) Box

OuterConstrain is similar to `Constraint` with the difference that it applies corrections

func (Box) Shift

func (b Box) Shift(x, y int) Box

Shift pushes a box by x,y.

func (Box) String

func (b Box) String() string

String returns a string representation of the box.

func (Box) Width

func (b Box) Width() int

Width returns the width

type Chart

type Chart struct {
	Title      string
	TitleStyle Style

	Width  int
	Height int
	DPI    float64

	Background Style
	Canvas     Style

	XAxis          XAxis
	YAxis          YAxis
	YAxisSecondary YAxis

	Font *truetype.Font

	Series   []Series
	Elements []Renderable
	// contains filtered or unexported fields
}

Chart is what we're drawing.

func (Chart) GetDPI

func (c Chart) GetDPI(defaults ...float64) float64

GetDPI returns the dpi for the chart.

func (Chart) GetFont

func (c Chart) GetFont() *truetype.Font

GetFont returns the text font.

func (Chart) GetHeight

func (c Chart) GetHeight() int

GetHeight returns the chart height or the default value.

func (Chart) GetWidth

func (c Chart) GetWidth() int

GetWidth returns the chart width or the default value.

func (Chart) Render

func (c Chart) Render(rp RendererProvider, w io.Writer) error

Render renders the chart with the given renderer to the given io.Writer.

type ContinuousSeries

type ContinuousSeries struct {
	Name  string
	Style Style

	YAxis YAxisType

	XValues []float64
	YValues []float64
}

ContinuousSeries represents a line on a chart.

func (ContinuousSeries) GetName

func (cs ContinuousSeries) GetName() string

GetName returns the name of the time series.

func (ContinuousSeries) GetStyle

func (cs ContinuousSeries) GetStyle() Style

GetStyle returns the line style.

func (ContinuousSeries) GetValue

func (cs ContinuousSeries) GetValue(index int) (float64, float64)

GetValue gets a value at a given index.

func (ContinuousSeries) GetValueFormatters

func (cs ContinuousSeries) GetValueFormatters() (x, y ValueFormatter)

GetValueFormatters returns value formatter defaults for the series.

func (ContinuousSeries) GetYAxis

func (cs ContinuousSeries) GetYAxis() YAxisType

GetYAxis returns which YAxis the series draws on.

func (ContinuousSeries) Len

func (cs ContinuousSeries) Len() int

Len returns the number of elements in the series.

func (ContinuousSeries) Render

func (cs ContinuousSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style)

Render renders the series.

type Float

type Float float64

Float is an alias for float64 that provides a better .String() method.

func (Float) String

func (f Float) String() string

String returns the string representation of a float.

type GridLine

type GridLine struct {
	IsMinor    bool
	IsVertical bool
	Style      Style
	Value      float64
}

GridLine is a line on a graph canvas.

func GenerateGridLines

func GenerateGridLines(ticks []Tick, isVertical bool) []GridLine

GenerateGridLines generates grid lines.

func (GridLine) Horizontal

func (gl GridLine) Horizontal() bool

Horizontal returns if the line is horizontal line or not.

func (GridLine) Major

func (gl GridLine) Major() bool

Major returns if the gridline is a `major` line.

func (GridLine) Minor

func (gl GridLine) Minor() bool

Minor returns if the gridline is a `minor` line.

func (GridLine) Render

func (gl GridLine) Render(r Renderer, canvasBox Box, ra Range)

Render renders the gridline

func (GridLine) Vertical

func (gl GridLine) Vertical() bool

Vertical returns if the line is vertical line or not.

type MovingAverageSeries

type MovingAverageSeries struct {
	Name  string
	Style Style
	YAxis YAxisType

	WindowSize  int
	InnerSeries ValueProvider
	// contains filtered or unexported fields
}

MovingAverageSeries is a computed series.

func (MovingAverageSeries) GetLastValue

func (mas MovingAverageSeries) GetLastValue() (x float64, y float64)

GetLastValue computes the last moving average value but walking back window size samples, and recomputing the last moving average chunk.

func (MovingAverageSeries) GetName

func (mas MovingAverageSeries) GetName() string

GetName returns the name of the time series.

func (MovingAverageSeries) GetStyle

func (mas MovingAverageSeries) GetStyle() Style

GetStyle returns the line style.

func (*MovingAverageSeries) GetValue

func (mas *MovingAverageSeries) GetValue(index int) (x float64, y float64)

GetValue gets a value at a given index.

func (MovingAverageSeries) GetWindowSize

func (mas MovingAverageSeries) GetWindowSize(defaults ...int) int

GetWindowSize returns the window size.

func (MovingAverageSeries) GetYAxis

func (mas MovingAverageSeries) GetYAxis() YAxisType

GetYAxis returns which YAxis the series draws on.

func (*MovingAverageSeries) Len

func (mas *MovingAverageSeries) Len() int

Len returns the number of elements in the series.

func (*MovingAverageSeries) Render

func (mas *MovingAverageSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style)

Render renders the series.

type Range

type Range struct {
	Min    float64
	Max    float64
	Domain int
}

Range represents a boundary for a set of numbers.

func (Range) Delta

func (r Range) Delta() float64

Delta returns the difference between the min and max value.

func (Range) GetRoundedRangeBounds

func (r Range) GetRoundedRangeBounds() (min, max float64)

GetRoundedRangeBounds returns some `prettified` range bounds.

func (Range) IsZero

func (r Range) IsZero() bool

IsZero returns if the range has been set or not.

func (Range) String

func (r Range) String() string

String returns a simple string for the range.

func (Range) Translate

func (r Range) Translate(value float64) int

Translate maps a given value into the range space.

type Renderable

type Renderable func(r Renderer, canvasBox Box)

Renderable is a function that can be called to render custom elements on the chart.

type Renderer

type Renderer interface {
	// GetDPI gets the DPI for the renderer.
	GetDPI() float64

	// SetDPI sets the DPI for the renderer.
	SetDPI(dpi float64)

	// SetStrokeColor sets the current stroke color.
	SetStrokeColor(drawing.Color)

	// SetFillColor sets the current fill color.
	SetFillColor(drawing.Color)

	// SetStrokeWidth sets the stroke width.
	SetStrokeWidth(width float64)

	// SetStrokeDashArray sets the stroke dash array.
	SetStrokeDashArray(dashArray []float64)

	// MoveTo moves the cursor to a given point.
	MoveTo(x, y int)

	// LineTo both starts a shape and draws a line to a given point
	// from the previous point.
	LineTo(x, y int)

	// Close finalizes a shape as drawn by LineTo.
	Close()

	// Stroke strokes the path.
	Stroke()

	// Fill fills the path, but does not stroke.
	Fill()

	// FillStroke fills and strokes a path.
	FillStroke()

	// Circle draws a circle at the given coords with a given radius.
	Circle(radius float64, x, y int)

	// SetFont sets a font for a text field.
	SetFont(*truetype.Font)

	// SetFontColor sets a font's color
	SetFontColor(drawing.Color)

	// SetFontSize sets the font size for a text field.
	SetFontSize(size float64)

	// Text draws a text blob.
	Text(body string, x, y int)

	// MeasureText measures text.
	MeasureText(body string) Box

	// Save writes the image to the given writer.
	Save(w io.Writer) error
}

Renderer represents the basic methods required to draw a chart.

func PNG

func PNG(width, height int) (Renderer, error)

PNG returns a new png/raster renderer.

func SVG

func SVG(width, height int) (Renderer, error)

SVG returns a new png/raster renderer.

type RendererProvider

type RendererProvider func(int, int) (Renderer, error)

RendererProvider is a function that returns a renderer.

type RingBuffer

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

RingBuffer is a fifo buffer that is backed by a pre-allocated array, instead of allocating a whole new node object for each element (which saves GC churn). Enqueue can be O(n), Dequeue can be O(1).

func NewRingBuffer

func NewRingBuffer() *RingBuffer

NewRingBuffer creates a new, empty, RingBuffer.

func NewRingBufferFromSlice

func NewRingBufferFromSlice(values []interface{}) *RingBuffer

NewRingBufferFromSlice createsa ring buffer out of a slice.

func NewRingBufferWithCapacity

func NewRingBufferWithCapacity(capacity int) *RingBuffer

NewRingBufferWithCapacity creates a new RingBuffer pre-allocated with the given capacity.

func (*RingBuffer) AsSlice

func (rb *RingBuffer) AsSlice() []interface{}

AsSlice returns the ring buffer, in order, as a slice.

func (*RingBuffer) Clear

func (rb *RingBuffer) Clear()

Clear removes all objects from the RingBuffer.

func (*RingBuffer) Dequeue

func (rb *RingBuffer) Dequeue() interface{}

Dequeue removes the first element from the RingBuffer.

func (*RingBuffer) Each

func (rb *RingBuffer) Each(consumer func(value interface{}))

Each calls the consumer for each element in the buffer.

func (*RingBuffer) Enqueue

func (rb *RingBuffer) Enqueue(object interface{})

Enqueue adds an element to the "back" of the RingBuffer.

func (*RingBuffer) Len

func (rb *RingBuffer) Len() int

Len returns the length of the ring buffer (as it is currently populated). Actual memory footprint may be different.

func (*RingBuffer) Peek

func (rb *RingBuffer) Peek() interface{}

Peek returns but does not remove the first element.

func (*RingBuffer) PeekBack

func (rb *RingBuffer) PeekBack() interface{}

PeekBack returns but does not remove the last element.

func (*RingBuffer) String

func (rb *RingBuffer) String() string

func (*RingBuffer) TotalLen

func (rb *RingBuffer) TotalLen() int

TotalLen returns the total size of the ring bufffer, including empty elements.

func (*RingBuffer) TrimExcess

func (rb *RingBuffer) TrimExcess()

TrimExcess resizes the buffer to better fit the contents.

type Series

type Series interface {
	GetYAxis() YAxisType
	GetStyle() Style
	Render(r Renderer, canvasBox Box, xrange, yrange Range, s Style)
}

Series is an alias to Renderable.

type Style

type Style struct {
	Show    bool
	Padding Box

	StrokeWidth     float64
	StrokeColor     drawing.Color
	StrokeDashArray []float64

	FillColor drawing.Color
	FontSize  float64
	FontColor drawing.Color
	Font      *truetype.Font
}

Style is a simple style set.

func (Style) GetFillColor

func (s Style) GetFillColor(defaults ...drawing.Color) drawing.Color

GetFillColor returns the fill color.

func (Style) GetFont

func (s Style) GetFont(defaults ...*truetype.Font) *truetype.Font

GetFont returns the font face.

func (Style) GetFontColor

func (s Style) GetFontColor(defaults ...drawing.Color) drawing.Color

GetFontColor gets the font size.

func (Style) GetFontSize

func (s Style) GetFontSize(defaults ...float64) float64

GetFontSize gets the font size.

func (Style) GetPadding

func (s Style) GetPadding(defaults ...Box) Box

GetPadding returns the padding.

func (Style) GetStrokeColor

func (s Style) GetStrokeColor(defaults ...drawing.Color) drawing.Color

GetStrokeColor returns the stroke color.

func (Style) GetStrokeDashArray

func (s Style) GetStrokeDashArray(defaults ...[]float64) []float64

GetStrokeDashArray returns the stroke dash array.

func (Style) GetStrokeWidth

func (s Style) GetStrokeWidth(defaults ...float64) float64

GetStrokeWidth returns the stroke width.

func (Style) IsZero

func (s Style) IsZero() bool

IsZero returns if the object is set or not.

func (Style) SVG

func (s Style) SVG(dpi float64) string

SVG returns the style as a svg style string.

func (Style) SVGFill

func (s Style) SVGFill() Style

SVGFill returns the fill components.

func (Style) SVGFillAndStroke

func (s Style) SVGFillAndStroke() Style

SVGFillAndStroke returns the fill and stroke components.

func (Style) SVGStroke

func (s Style) SVGStroke() Style

SVGStroke returns the stroke components.

func (Style) SVGText

func (s Style) SVGText() Style

SVGText returns just the text components of the style.

func (Style) WithDefaultsFrom

func (s Style) WithDefaultsFrom(defaults Style) (final Style)

WithDefaultsFrom coalesces two styles into a new style.

type Tick

type Tick struct {
	Value float64
	Label string
}

Tick represents a label on an axis.

func GenerateTicksWithStep

func GenerateTicksWithStep(ra Range, step float64, vf ValueFormatter) []Tick

GenerateTicksWithStep generates a set of ticks.

type Ticks

type Ticks []Tick

Ticks is an array of ticks.

func (Ticks) Len

func (t Ticks) Len() int

Len returns the length of the ticks set.

func (Ticks) Less

func (t Ticks) Less(i, j int) bool

Less returns if i's value is less than j's value.

func (Ticks) Swap

func (t Ticks) Swap(i, j int)

Swap swaps two elements.

type TimeSeries

type TimeSeries struct {
	Name  string
	Style Style

	YAxis YAxisType

	XValues []time.Time
	YValues []float64
}

TimeSeries is a line on a chart.

func (TimeSeries) GetName

func (ts TimeSeries) GetName() string

GetName returns the name of the time series.

func (TimeSeries) GetStyle

func (ts TimeSeries) GetStyle() Style

GetStyle returns the line style.

func (TimeSeries) GetValue

func (ts TimeSeries) GetValue(index int) (x float64, y float64)

GetValue gets a value at a given index.

func (TimeSeries) GetValueFormatters

func (ts TimeSeries) GetValueFormatters() (x, y ValueFormatter)

GetValueFormatters returns value formatter defaults for the series.

func (TimeSeries) GetYAxis

func (ts TimeSeries) GetYAxis() YAxisType

GetYAxis returns which YAxis the series draws on.

func (TimeSeries) Len

func (ts TimeSeries) Len() int

Len returns the number of elements in the series.

func (TimeSeries) Render

func (ts TimeSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style)

Render renders the series.

type ValueFormatter

type ValueFormatter func(v interface{}) string

ValueFormatter is a function that takes a value and produces a string.

type ValueFormatterProvider

type ValueFormatterProvider interface {
	GetValueFormatters() (x, y ValueFormatter)
}

ValueFormatterProvider is a series that has custom formatters.

type ValueProvider

type ValueProvider interface {
	Len() int
	GetValue(index int) (float64, float64)
}

ValueProvider is a type that produces values.

type XAxis

type XAxis struct {
	Name           string
	Style          Style
	ValueFormatter ValueFormatter
	Range          Range
	Ticks          []Tick

	GridLines      []GridLine
	GridMajorStyle Style
	GridMinorStyle Style
}

XAxis represents the horizontal axis.

func (XAxis) GetGridLines

func (xa XAxis) GetGridLines(ticks []Tick) []GridLine

GetGridLines returns the gridlines for the axis.

func (XAxis) GetName

func (xa XAxis) GetName() string

GetName returns the name.

func (XAxis) GetStyle

func (xa XAxis) GetStyle() Style

GetStyle returns the style.

func (XAxis) GetTicks

func (xa XAxis) GetTicks(r Renderer, ra Range, defaults Style, vf ValueFormatter) []Tick

GetTicks returns the ticks for a series. It coalesces between user provided ticks and generated ticks.

func (XAxis) Measure

func (xa XAxis) Measure(r Renderer, canvasBox Box, ra Range, defaults Style, ticks []Tick) Box

Measure returns the bounds of the axis.

func (XAxis) Render

func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range, defaults Style, ticks []Tick)

Render renders the axis

type YAxis

type YAxis struct {
	Name  string
	Style Style

	Zero GridLine

	AxisType YAxisType

	ValueFormatter ValueFormatter
	Range          Range
	Ticks          []Tick

	GridLines      []GridLine
	GridMajorStyle Style
	GridMinorStyle Style
}

YAxis is a veritcal rule of the range. There can be (2) y-axes; a primary and secondary.

func (YAxis) GetGridLines

func (ya YAxis) GetGridLines(ticks []Tick) []GridLine

GetGridLines returns the gridlines for the axis.

func (YAxis) GetName

func (ya YAxis) GetName() string

GetName returns the name.

func (YAxis) GetStyle

func (ya YAxis) GetStyle() Style

GetStyle returns the style.

func (YAxis) GetTicks

func (ya YAxis) GetTicks(r Renderer, ra Range, defaults Style, vf ValueFormatter) []Tick

GetTicks returns the ticks for a series. It coalesces between user provided ticks and generated ticks.

func (YAxis) Measure

func (ya YAxis) Measure(r Renderer, canvasBox Box, ra Range, defaults Style, ticks []Tick) Box

Measure returns the bounds of the axis.

func (YAxis) Render

func (ya YAxis) Render(r Renderer, canvasBox Box, ra Range, defaults Style, ticks []Tick)

Render renders the axis.

type YAxisType

type YAxisType int

YAxisType is a type of y-axis; it can either be primary or secondary.

const (
	// YAxisPrimary is the primary axis.
	YAxisPrimary YAxisType = 0
	// YAxisSecondary is the secondary axis.
	YAxisSecondary YAxisType = 1
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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