snapshot.

This commit is contained in:
Will Charczuk 2016-07-10 01:11:47 -07:00
parent 7bb82ae691
commit e9a36274ac
23 changed files with 551 additions and 445 deletions

26
annotation_series.go Normal file
View File

@ -0,0 +1,26 @@
package chart
// Annotation is a label on the chart.
type Annotation struct {
X, Y float64
Label string
}
// AnnotationSeries is a series of labels on the chart.
type AnnotationSeries struct {
Name string
Style Style
YAxis YAxisType
Annotations []Annotation
}
// Render draws the series.
func (as AnnotationSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range) {
if as.Style.Show {
for _, a := range as.Annotations {
lx := xrange.Translate(a.X) + canvasBox.Left
ly := yrange.Translate(a.Y) + canvasBox.Top
DrawAnnotation(r, canvasBox, xrange, yrange, as.Style, lx, ly, a.Label)
}
}
}

59
axis.go Normal file
View File

@ -0,0 +1,59 @@
package chart
// YAxisType is a type of y-axis; it can either be primary or secondary.
type YAxisType int
const (
// YAxisPrimary is the primary axis.
YAxisPrimary YAxisType = 0
// YAxisSecondary is the secondary axis.
YAxisSecondary YAxisType = 1
)
// Axis is a chart feature detailing what values happen where.
type Axis interface {
GetName() string
GetStyle() Style
Render(c *Chart, r Renderer, canvasBox Box, ra Range)
}
// axis represents the basics of an axis implementation.
type axis struct {
Name string
Style Style
ValueFormatter ValueFormatter
Range Range
Ticks []Tick
}
func (a axis) GetName() string {
return a.Name
}
func (a axis) GetStyle() Style {
return a.Style
}
func (a axis) getTicks(ra Range) []Tick {
if len(a.Ticks) > 0 {
return a.Ticks
}
return a.generateTicks(ra)
}
func (a axis) generateTicks(ra Range) []Tick {
step := a.getTickStep(ra)
return a.generateTicksWithStep(ra, step)
}
func (a axis) getTickCount(ra Range) int {
return 0
}
func (a axis) getTickStep(ra Range) float64 {
return 0.0
}
func (a axis) generateTicksWithStep(ra Range, step float64) []Tick {
return []Tick{}
}

2
box.go
View File

@ -20,7 +20,7 @@ func (b Box) IsZero() bool {
// String returns a string representation of the box.
func (b Box) String() string {
return fmt.Sprintf("Box(%d,%d,%d,%d)", b.Top, b.Left, b.Right, b.Bottom)
return fmt.Sprintf("box(%d,%d,%d,%d)", b.Top, b.Left, b.Right, b.Bottom)
}
// GetTop returns a coalesced value with a default.

329
chart.go
View File

@ -3,7 +3,6 @@ package chart
import (
"errors"
"io"
"math"
"github.com/golang/freetype/truetype"
)
@ -19,10 +18,10 @@ type Chart struct {
Background Style
Canvas Style
Axes Style
XRange Range
YRange Range
XAxis XAxis
YAxis YAxis
YAxisSecondary YAxis
Font *truetype.Font
Series []Series
@ -68,92 +67,28 @@ func (c *Chart) Render(rp RendererProvider, w io.Writer) error {
r.SetFont(font)
r.SetDPI(c.GetDPI(DefaultDPI))
canvasBox := c.calculateCanvasBox(r)
xrange, yrange := c.initRanges(canvasBox)
xrange, yrange, yrangeAlt := c.getRanges()
canvasBox := c.getCanvasBox(r, xrange, yrange, yrangeAlt)
xrange, yrange, yrangeAlt = c.getRangeDomains(canvasBox, xrange, yrange, yrangeAlt)
c.drawBackground(r)
c.drawCanvas(r, canvasBox)
c.drawAxes(r, canvasBox, xrange, yrange)
c.drawAxes(r, canvasBox, xrange, yrange, yrangeAlt)
for index, series := range c.Series {
c.drawSeries(r, canvasBox, series, xrange, yrange)
c.drawSeries(r, canvasBox, xrange, yrange, yrangeAlt, series, index)
}
c.drawTitle(r)
return r.Save(w)
}
func (c Chart) getAxisWidth() int {
asw := 0
if c.Axes.Show {
asw = int(c.Axes.GetStrokeWidth(DefaultAxisLineWidth))
}
return asw
}
func (c Chart) calculateCanvasBox(r Renderer) Box {
dpr := DefaultBackgroundPadding.Right
finalLabelWidth := c.calculateFinalLabelWidth(r)
if finalLabelWidth > dpr {
dpr = finalLabelWidth
}
axisBottomHeight := c.calculateBottomLabelHeight()
dpb := DefaultBackgroundPadding.Bottom
if dpb < axisBottomHeight {
dpb = axisBottomHeight
}
cb := Box{
Top: c.Background.Padding.GetTop(DefaultBackgroundPadding.Top),
Left: c.Background.Padding.GetLeft(DefaultBackgroundPadding.Left),
Right: c.Width - c.Background.Padding.GetRight(dpr),
Bottom: c.Height - c.Background.Padding.GetBottom(dpb),
}
cb.Height = cb.Bottom - cb.Top
cb.Width = cb.Right - cb.Left
return cb
}
func (c Chart) calculateFinalLabelWidth(r Renderer) int {
var finalLabelText string
for _, s := range c.Series {
if vs, isValueProvider := s.(ValueProvider); isValueProvider {
_, lv := vs.GetValue(vs.Len() - 1)
var ll string
if c.YRange.Formatter != nil {
ll = c.YRange.Formatter(lv)
} else if fp, isFormatterProvider := s.(FormatterProvider); isFormatterProvider {
ll = fp.GetYFormatter()(lv)
}
if len(finalLabelText) < len(ll) {
finalLabelText = ll
}
}
}
r.SetFontSize(c.FinalValueLabel.GetFontSize(DefaultFinalLabelFontSize))
textWidth, _ := r.MeasureText(finalLabelText)
asw := c.getAxisWidth()
pl := c.FinalValueLabel.Padding.GetLeft(DefaultFinalLabelPadding.Left)
pr := c.FinalValueLabel.Padding.GetRight(DefaultFinalLabelPadding.Right)
lsw := int(c.FinalValueLabel.GetStrokeWidth(DefaultAxisLineWidth))
return DefaultYAxisMargin +
pl + pr +
textWidth + asw + 2*lsw
}
func (c Chart) calculateBottomLabelHeight() int {
if c.Axes.Show {
return c.getAxisWidth() + int(math.Ceil(c.Axes.GetFontSize(DefaultAxisFontSize))) + DefaultXAxisMargin
}
return 0
}
func (c Chart) initRanges(canvasBox Box) (xrange Range, yrange Range) {
func (c Chart) getRanges() (xrange, yrange, yrangeAlt Range) {
//iterate over each series, pull out the min/max for x,y
var didSetFirstValues bool
var globalMinY, globalMinX float64
var globalMaxY, globalMaxX float64
var globalMinX, globalMaxX float64
var globalMinY, globalMaxY float64
var globalMinYA, globalMaxYA float64
for _, s := range c.Series {
if vp, isValueProvider := s.(ValueProvider); isValueProvider {
seriesLength := vp.Len()
@ -163,65 +98,130 @@ func (c Chart) initRanges(canvasBox Box) (xrange Range, yrange Range) {
if globalMinX > vx {
globalMinX = vx
}
if globalMinY > vy {
globalMinY = vy
}
if globalMaxX < vx {
globalMaxX = vx
}
if globalMaxY < vy {
globalMaxY = vy
if s.GetYAxis() == YAxisPrimary {
if globalMinY > vy {
globalMinY = vy
}
if globalMaxY < vy {
globalMaxY = vy
}
} else if s.GetYAxis() == YAxisSecondary {
if globalMinYA > vy {
globalMinYA = vy
}
if globalMaxYA < vy {
globalMaxYA = vy
}
}
} else {
globalMinX, globalMaxX = vx, vx
globalMinY, globalMaxY = vy, vy
if s.GetYAxis() == YAxisPrimary {
globalMinY, globalMaxY = vy, vy
} else if s.GetYAxis() == YAxisSecondary {
globalMinYA, globalMaxYA = vy, vy
}
didSetFirstValues = true
}
}
}
if fp, isFormatterProvider := s.(FormatterProvider); isFormatterProvider {
if xrange.Formatter == nil {
xrange.Formatter = fp.GetXFormatter()
}
if yrange.Formatter == nil {
yrange.Formatter = fp.GetYFormatter()
}
}
}
if c.XRange.IsZero() {
if !c.XAxis.Range.IsZero() {
xrange.Min = c.XAxis.Range.Min
xrange.Max = c.XAxis.Range.Max
} else {
xrange.Min = globalMinX
xrange.Max = globalMaxX
} else {
xrange.Min = c.XRange.Min
xrange.Max = c.XRange.Max
}
if c.XRange.Formatter != nil {
xrange.Formatter = c.XRange.Formatter
}
if c.XRange.Ticks != nil {
xrange.Ticks = c.XRange.Ticks
}
xrange.Domain = canvasBox.Width
if c.YRange.IsZero() {
if !c.YAxis.Range.IsZero() {
yrange.Min = c.YAxis.Range.Min
yrange.Max = c.YAxis.Range.Max
} else {
yrange.Min = globalMinY
yrange.Max = globalMaxY
} else {
yrange.Min = c.YRange.Min
yrange.Max = c.YRange.Max
}
if c.YRange.Formatter != nil {
yrange.Formatter = c.YRange.Formatter
}
if c.YRange.Ticks != nil {
yrange.Ticks = c.YRange.Ticks
}
yrange.Domain = canvasBox.Height
return
}
func (c Chart) getCanvasBox(r Renderer, xrange, yrange, yrangeAlt Range) Box {
dpl := c.Background.Padding.GetLeft(DefaultBackgroundPadding.Left)
dpr := c.Background.Padding.GetRight(DefaultBackgroundPadding.Right)
dpb := c.Background.Padding.GetBottom(DefaultBackgroundPadding.Bottom)
if c.YAxisSecondary.Style.Show {
dpl = c.getYAxisSecondaryWidth(r, yrangeAlt)
}
if c.YAxis.Style.Show {
dpr = c.getYAxisWidth(r, yrange)
}
if c.XAxis.Style.Show {
dpb = c.getXAxisHeight(r, xrange)
}
cb := Box{
Top: c.Background.Padding.GetTop(DefaultBackgroundPadding.Top),
Left: dpl,
Right: c.Width - dpr,
Bottom: c.Height - dpb,
}
cb.Height = cb.Bottom - cb.Top
cb.Width = cb.Right - cb.Left
return cb
}
func (c Chart) getYAxisSecondaryWidth(r Renderer, ra Range) int {
var ll string
ticks := c.YAxisSecondary.getTicks(ra)
for _, t := range ticks {
if len(t.Label) > len(ll) {
ll = t.Label
}
}
r.SetFontSize(c.YAxisSecondary.Style.GetFontSize(DefaultFontSize))
r.SetFont(c.YAxisSecondary.Style.GetFont(c.Font))
tw, _ := r.MeasureText(ll)
return tw + DefaultYAxisMargin
}
func (c Chart) getYAxisWidth(r Renderer, ra Range) int {
var ll string
ticks := c.YAxis.getTicks(ra)
for _, t := range ticks {
if len(t.Label) > len(ll) {
ll = t.Label
}
}
r.SetFontSize(c.YAxis.Style.GetFontSize(DefaultFontSize))
r.SetFont(c.YAxis.Style.GetFont(c.Font))
tw, _ := r.MeasureText(ll)
return tw + DefaultYAxisMargin
}
func (c Chart) getXAxisHeight(r Renderer, ra Range) int {
r.SetFontSize(c.XAxis.Style.GetFontSize(DefaultFontSize))
r.SetFont(c.XAxis.Style.GetFont(c.Font))
var tl int
ticks := c.YAxis.getTicks(ra)
for _, t := range ticks {
_, lh := r.MeasureText(t.Label)
if lh > tl {
tl = lh
}
}
return tl + DefaultXAxisMargin
}
func (c Chart) getRangeDomains(canvasBox Box, xrange, yrange, yrangeAlt Range) (Range, Range, Range) {
xrange.Domain = canvasBox.Width
yrange.Domain = canvasBox.Height
yrangeAlt.Domain = canvasBox.Height
return xrange, yrange, yrangeAlt
}
func (c Chart) drawBackground(r Renderer) {
r.SetFillColor(c.Background.GetFillColor(DefaultBackgroundColor))
r.SetStrokeColor(c.Background.GetStrokeColor(DefaultBackgroundStrokeColor))
@ -248,88 +248,35 @@ func (c Chart) drawCanvas(r Renderer, canvasBox Box) {
r.FillStroke()
}
func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange Range) {
if c.Axes.Show {
r.SetStrokeColor(c.Axes.GetStrokeColor(DefaultAxisColor))
r.SetStrokeWidth(c.Axes.GetStrokeWidth(DefaultStrokeWidth))
r.MoveTo(canvasBox.Left, canvasBox.Bottom)
r.LineTo(canvasBox.Right, canvasBox.Bottom)
r.LineTo(canvasBox.Right, canvasBox.Top)
r.Stroke()
c.drawXAxisLabels(r, canvasBox, xrange)
c.drawYAxisLabels(r, canvasBox, yrange)
func (c Chart) drawAxes(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range) {
if c.XAxis.Style.Show {
c.XAxis.Render(r, canvasBox, xrange)
}
if c.YAxis.Style.Show {
c.YAxis.Render(r, canvasBox, yrange, YAxisPrimary)
}
if c.YAxisSecondary.Style.Show {
c.YAxisSecondary.Render(r, canvasBox, yrangeAlt, YAxisSecondary)
}
}
func (c Chart) generateRangeTicks(r Range, tickCount int, offset float64) []Tick {
var ticks []Tick
rangeTicks := Slices(tickCount, r.Max-r.Min)
for _, rv := range rangeTicks {
ticks = append(ticks, Tick{
RangeValue: rv + offset,
Label: r.Format(rv + offset),
})
}
return ticks
}
func (c Chart) drawYAxisLabels(r Renderer, canvasBox Box, yrange Range) {
tickFontSize := c.Axes.GetFontSize(DefaultAxisFontSize)
asw := c.getAxisWidth()
tx := canvasBox.Right + DefaultYAxisMargin + asw
r.SetFontColor(c.Axes.GetFontColor(DefaultAxisColor))
r.SetFontSize(tickFontSize)
ticks := yrange.Ticks
if ticks == nil {
minimumTickHeight := tickFontSize + DefaultMinimumTickVerticalSpacing
tickCount := int(math.Floor(float64(yrange.Domain) / float64(minimumTickHeight)))
if tickCount > DefaultMaxTickCount {
tickCount = DefaultMaxTickCount
}
ticks = c.generateRangeTicks(yrange, tickCount, yrange.Min)
}
for _, t := range ticks {
v := t.RangeValue
y := yrange.Translate(v)
ty := int(y)
r.Text(t.Label, tx, ty)
func (c Chart) getSeriesDefaults(seriesIndex int) Style {
strokeColor := GetDefaultSeriesStrokeColor(seriesIndex)
return Style{
StrokeColor: strokeColor,
StrokeWidth: DefaultStrokeWidth,
FillColor: strokeColor.WithAlpha(100),
Font: c.Font,
FontSize: DefaultFontSize,
}
}
func (c Chart) drawXAxisLabels(r Renderer, canvasBox Box, xrange Range) {
tickFontSize := c.Axes.GetFontSize(DefaultAxisFontSize)
ty := canvasBox.Bottom + DefaultXAxisMargin + int(tickFontSize)
r.SetFontColor(c.Axes.GetFontColor(DefaultAxisColor))
r.SetFontSize(tickFontSize)
ticks := xrange.Ticks
if ticks == nil {
maxLabelWidth := 60
minimumTickWidth := maxLabelWidth + DefaultMinimumTickHorizontalSpacing
tickCount := int(math.Floor(float64(xrange.Domain) / float64(minimumTickWidth)))
if tickCount > DefaultMaxTickCount {
tickCount = DefaultMaxTickCount
}
ticks = c.generateRangeTicks(xrange, tickCount, xrange.Min)
func (c Chart) drawSeries(r Renderer, canvasBox Box, xrange, yrange, yrangeAlt Range, s Series, seriesIndex int) {
if s.GetYAxis() == YAxisPrimary {
s.Render(r, canvasBox, xrange, yrange, c.getSeriesDefaults(seriesIndex))
} else if s.GetYAxis() == YAxisSecondary {
s.Render(r, canvasBox, xrange, yrange, c.getSeriesDefaults(seriesIndex))
}
for _, t := range ticks {
v := t.RangeValue
x := xrange.Translate(v)
tx := canvasBox.Left + int(x)
r.Text(t.Label, tx, ty)
}
}
func (c Chart) drawSeries(r Renderer, canvasBox Box, s Series, xrange, yrange Range) {
return s.Render(&c, r, canvasBox, xrange, yrange)
}
func (c Chart) drawTitle(r Renderer) error {

View File

@ -1,16 +1,11 @@
package chart
import (
"fmt"
"github.com/blendlabs/go-util"
)
// ContinuousSeries represents a line on a chart.
type ContinuousSeries struct {
Name string
Style Style
FinalValueLabel Style
Name string
Style Style
YAxis YAxisType
XValues []float64
YValues []float64
@ -36,35 +31,8 @@ func (cs ContinuousSeries) GetValue(index int) (float64, float64) {
return cs.XValues[index], cs.YValues[index]
}
// GetXFormatter returns the xs value formatter.
func (cs ContinuousSeries) GetXFormatter() Formatter {
return func(v interface{}) string {
if typed, isTyped := v.(float64); isTyped {
return fmt.Sprintf("%0.2f", typed)
}
return util.StringEmpty
}
}
// GetYFormatter returns the y value formatter.
func (cs ContinuousSeries) GetYFormatter() Formatter {
return cs.GetXFormatter()
}
// Render renders the series.
func (cs ContinuousSeries) Render(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range) error {
DrawLineSeries(c, r, canvasBox, xrange, yrange, cs)
if cs.FinalValueLabel.Show {
asw := 0
if c.Axes.Show {
asw = int(c.Axes.GetStrokeWidth(DefaultAxisLineWidth))
}
_, lv := cs.GetValue(cs.Len() - 1)
ll := yrange.Format(lv)
lx := canvasBox.Right + asw
ly := yrange.Translate(lv) + canvasBox.Top
DrawAnnotation(c, r, canvasBox, xrange, yrange, cs.FinalValueLabel, lx, ly, ll)
}
func (cs ContinuousSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) {
style := cs.Style.WithDefaultsFrom(defaults)
DrawLineSeries(r, canvasBox, xrange, yrange, style, cs)
}

95
drawing_helpers.go Normal file
View File

@ -0,0 +1,95 @@
package chart
import "math"
// DrawLineSeries draws a line series with a renderer.
func DrawLineSeries(r Renderer, canvasBox Box, xrange, yrange Range, s Style, vs ValueProvider) {
if vs.Len() == 0 {
return
}
cx := canvasBox.Left
cy := canvasBox.Top
cb := canvasBox.Bottom
cw := canvasBox.Width
v0x, v0y := vs.GetValue(0)
x0 := cw - xrange.Translate(v0x)
y0 := yrange.Translate(v0y)
var vx, vy float64
var x, y int
fill := s.GetFillColor()
if !fill.IsZero() {
r.SetFillColor(fill)
r.MoveTo(x0+cx, y0+cy)
for i := 1; i < vs.Len(); i++ {
vx, vy = vs.GetValue(i)
x = cw - xrange.Translate(vx)
y = yrange.Translate(vy)
r.LineTo(x+cx, y+cy)
}
r.LineTo(x+cx, cb)
r.LineTo(x0+cx, cb)
r.Close()
r.Fill()
}
stroke := s.GetStrokeColor()
r.SetStrokeColor(stroke)
r.SetStrokeWidth(s.GetStrokeWidth(DefaultStrokeWidth))
r.MoveTo(x0+cx, y0+cy)
for i := 1; i < vs.Len(); i++ {
vx, vy = vs.GetValue(i)
x = cw - xrange.Translate(vx)
y = yrange.Translate(vy)
r.LineTo(x+cx, y+cy)
}
r.Stroke()
}
// DrawAnnotation draws an anotation with a renderer.
func DrawAnnotation(r Renderer, canvasBox Box, xrange, yrange Range, s Style, lx, ly int, label string) {
r.SetFontSize(s.GetFontSize(DefaultAnnotationFontSize))
textWidth, _ := r.MeasureText(label)
textHeight := int(math.Floor(DefaultAnnotationFontSize))
halfTextHeight := textHeight >> 1
pt := s.Padding.GetTop(DefaultAnnotationPadding.Top)
pl := s.Padding.GetLeft(DefaultAnnotationPadding.Left)
pr := s.Padding.GetRight(DefaultAnnotationPadding.Right)
pb := s.Padding.GetBottom(DefaultAnnotationPadding.Bottom)
textX := lx + pl + DefaultAnnotationDeltaWidth
textY := ly + halfTextHeight
ltlx := lx + pl + DefaultAnnotationDeltaWidth
ltly := ly - (pt + halfTextHeight)
ltrx := lx + pl + pr + textWidth
ltry := ly - (pt + halfTextHeight)
lbrx := lx + pl + pr + textWidth
lbry := ly + (pb + halfTextHeight)
lblx := lx + DefaultAnnotationDeltaWidth
lbly := ly + (pb + halfTextHeight)
//draw the shape...
r.SetFillColor(s.GetFillColor(DefaultAnnotationFillColor))
r.SetStrokeColor(s.GetStrokeColor())
r.SetStrokeWidth(s.GetStrokeWidth())
r.MoveTo(lx, ly)
r.LineTo(ltlx, ltly)
r.LineTo(ltrx, ltry)
r.LineTo(lbrx, lbry)
r.LineTo(lblx, lbly)
r.LineTo(lx, ly)
r.Close()
r.FillStroke()
r.SetFontColor(s.GetFontColor(DefaultTextColor))
r.Text(label, textX, textY)
}

View File

@ -1,4 +0,0 @@
package chart
// Formatter is a function that takes a value and produces a string.
type Formatter func(v interface{}) string

View File

@ -3,23 +3,13 @@ package chart
import (
"fmt"
"math"
"github.com/blendlabs/go-util"
)
// Tick represents a label on an axis.
type Tick struct {
RangeValue float64
Label string
}
// Range represents a continuous range,
// Range represents a boundary for a set of numbers.
type Range struct {
Min float64
Max float64
Domain int
Ticks []Tick
Formatter Formatter
Min float64
Max float64
Domain int
}
// IsZero returns if the range has been set or not.
@ -37,14 +27,6 @@ func (r Range) String() string {
return fmt.Sprintf("Range [%.2f,%.2f] => %d", r.Min, r.Max, r.Domain)
}
// Format formats the value based on the range's formatter.
func (r Range) Format(v interface{}) string {
if r.Formatter != nil {
return r.Formatter(v)
}
return util.StringEmpty
}
// Translate maps a given value into the range space.
// An example would be a 600 px image, with a min of 10 and a max of 100.
// Translate(50) would yield (50.0/90.0)*600 ~= 333.33

View File

@ -33,6 +33,11 @@ type rasterRenderer struct {
f *truetype.Font
}
// GetDPI returns the dpi.
func (rr *rasterRenderer) GetDPI() float64 {
return rr.gc.GetDPI()
}
// SetDPI implements the interface method.
func (rr *rasterRenderer) SetDPI(dpi float64) {
rr.gc.SetDPI(dpi)

6
renderable.go Normal file
View File

@ -0,0 +1,6 @@
package chart
// Renderable is a type that can be rendered onto a chart.
type Renderable interface {
Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style)
}

View File

@ -7,11 +7,11 @@ import (
"github.com/wcharczuk/go-chart/drawing"
)
// RendererProvider is a function that returns a renderer.
type RendererProvider func(int, int) (Renderer, error)
// Renderer represents the basic methods required to draw a chart.
type Renderer interface {
// GetDPI returns the dpi for the renderer.
GetDPI() float64
// SetDPI sets the DPI for the renderer.
SetDPI(dpi float64)

4
renderer_provider.go Normal file
View File

@ -0,0 +1,4 @@
package chart
// RendererProvider is a function that returns a renderer.
type RendererProvider func(int, int) (Renderer, error)

116
series.go
View File

@ -1,117 +1,7 @@
package chart
import "math"
// Series is a entity data set. It constitutes an item to draw on the chart.
// The series interface is the bare minimum you need to implement to draw something on a chart.
// Series is an alias to Renderable.
type Series interface {
GetName() string
GetStyle() Style
Render(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range) error
}
// ValueProvider is a series that is a set of values.
type ValueProvider interface {
Len() int
GetValue(index int) (float64, float64)
}
// FormatterProvider is a series that has custom formatters.
type FormatterProvider interface {
GetXFormatter() Formatter
GetYFormatter() Formatter
}
// DrawLineSeries draws a line series with a renderer.
func DrawLineSeries(c *Chart, r Renderer, canvasBox Box, xrange, yrange Range, vs ValueProvider) error {
if vs.Len() == 0 {
return
}
cx := canvasBox.Left
cy := canvasBox.Top
cb := canvasBox.Bottom
cw := canvasBox.Width
v0x, v0y := vs.GetValue(0)
x0 := cw - xrange.Translate(v0x)
y0 := yrange.Translate(v0y)
var vx, vy float64
var x, y int
fill := s.GetStyle().GetFillColor()
if !fill.IsZero() {
r.SetFillColor(fill)
r.MoveTo(x0+cx, y0+cy)
for i := 1; i < vs.Len(); i++ {
vx, vy = vs.GetValue(i)
x = cw - xrange.Translate(vx)
y = yrange.Translate(vy)
r.LineTo(x+cx, y+cy)
}
r.LineTo(x+cx, cb)
r.LineTo(x0+cx, cb)
r.Close()
r.Fill()
}
stroke := s.GetStyle().GetStrokeColor(GetDefaultSeriesStrokeColor(index))
r.SetStrokeColor(stroke)
r.SetStrokeWidth(s.GetStyle().GetStrokeWidth(DefaultStrokeWidth))
r.MoveTo(x0+cx, y0+cy)
for i := 1; i < vs.Len(); i++ {
vx, vy = vs.GetValue(i)
x = cw - xrange.Translate(vx)
y = yrange.Translate(vy)
r.LineTo(x+cx, y+cy)
}
r.Stroke()
}
// DrawAnnotation draws an anotation with a renderer.
func DrawAnnotation(c *Chart, r Renderer, canvasBox Box, xrange, yrange, s Style, lx, ly int, lv string) {
py := canvasBox.Top
r.SetFontSize(s.GetFontSize(DefaultFinalLabelFontSize))
textWidth, _ := r.MeasureText(ll)
textHeight := int(math.Floor(DefaultFinalLabelFontSize))
halfTextHeight := textHeight >> 1
pt := s.Padding.GetTop(DefaultFinalLabelPadding.Top)
pl := s.Padding.GetLeft(DefaultFinalLabelPadding.Left)
pr := s.Padding.GetRight(DefaultFinalLabelPadding.Right)
pb := s.Padding.GetBottom(DefaultFinalLabelPadding.Bottom)
textX := lx + pl + DefaultFinalLabelDeltaWidth
textY := ly + halfTextHeight
ltlx := lx + pl + DefaultFinalLabelDeltaWidth
ltly := ly - (pt + halfTextHeight)
ltrx := lx + pl + pr + textWidth
ltry := ly - (pt + halfTextHeight)
lbrx := lx + pl + pr + textWidth
lbry := ly + (pb + halfTextHeight)
lblx := lx + DefaultFinalLabelDeltaWidth
lbly := ly + (pb + halfTextHeight)
//draw the shape...
r.SetFillColor(s.GetFillColor(DefaultAnnotationFillColor))
r.SetStrokeColor(s.GetStrokeColor())
r.SetStrokeWidth(s.GetStrokeWidth())
r.MoveTo(lx, ly)
r.LineTo(ltlx, ltly)
r.LineTo(ltrx, ltry)
r.LineTo(lbrx, lbry)
r.LineTo(lblx, lbly)
r.LineTo(cx, ly)
r.Close()
r.FillStroke()
r.SetFontColor(s.GetFontColor(DefaultTextColor))
r.Text(ll, textX, textY)
GetYAxis() YAxisType
Renderable
}

View File

@ -1,30 +0,0 @@
package chart
import (
"testing"
"time"
"github.com/blendlabs/go-assert"
)
func TestTimeSeriesGetValue(t *testing.T) {
assert := assert.New(t)
ts := TimeSeries{
Name: "Test",
XValues: []time.Time{
time.Now().AddDate(0, 0, -5),
time.Now().AddDate(0, 0, -4),
time.Now().AddDate(0, 0, -3),
time.Now().AddDate(0, 0, -2),
time.Now().AddDate(0, 0, -1),
},
YValues: []float64{
1.0, 2.0, 3.0, 4.0, 5.0,
},
}
x0, y0 := ts.GetValue(0)
assert.NotZero(x0)
assert.Equal(1.0, y0)
}

View File

@ -4,23 +4,28 @@ import (
"fmt"
"strings"
"github.com/golang/freetype/truetype"
"github.com/wcharczuk/go-chart/drawing"
)
// Style is a simple style set.
type Style struct {
Show bool
StrokeColor drawing.Color
FillColor drawing.Color
Show bool
Padding Box
StrokeWidth float64
FontSize float64
FontColor drawing.Color
Padding Box
StrokeColor drawing.Color
FillColor drawing.Color
FontSize float64
FontColor drawing.Color
Font *truetype.Font
}
// IsZero returns if the object is set or not.
func (s Style) IsZero() bool {
return s.StrokeColor.IsZero() && s.FillColor.IsZero() && s.StrokeWidth == 0 && s.FontSize == 0
return s.StrokeColor.IsZero() && s.FillColor.IsZero() && s.StrokeWidth == 0 && s.FontSize == 0 && s.Font == nil
}
// GetStrokeColor returns the stroke color.
@ -78,6 +83,39 @@ func (s Style) GetFontColor(defaults ...drawing.Color) drawing.Color {
return s.FontColor
}
// GetFont returns the font face.
func (s Style) GetFont(defaults ...*truetype.Font) *truetype.Font {
if s.Font == nil {
if len(defaults) > 0 {
return defaults[0]
}
return nil
}
return s.Font
}
// GetPadding returns the padding.
func (s Style) GetPadding(defaults ...Box) Box {
if s.Padding.IsZero() {
if len(defaults) > 0 {
return defaults[0]
}
return Box{}
}
return s.Padding
}
// WithDefaultsFrom coalesces two styles into a new style.
func (s Style) WithDefaultsFrom(defaults Style) (final Style) {
final.FillColor = s.GetFillColor(defaults.FillColor)
final.FontColor = s.GetFontColor(defaults.FontColor)
final.Font = s.GetFont(defaults.Font)
final.Padding = s.GetPadding(defaults.Padding)
final.StrokeColor = s.GetStrokeColor(defaults.StrokeColor)
final.StrokeWidth = s.GetStrokeWidth(defaults.StrokeWidth)
return
}
// SVG returns the style as a svg style string.
func (s Style) SVG(dpi float64) string {
sw := s.StrokeWidth

25
tick.go Normal file
View File

@ -0,0 +1,25 @@
package chart
// Tick represents a label on an axis.
type Tick struct {
Value float64
Label string
}
// Ticks is an array of ticks.
type Ticks []Tick
// Len returns the length of the ticks set.
func (t Ticks) Len() int {
return len(t)
}
// Swap swaps two elements.
func (t Ticks) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
// Less returns if i's value is less than j's value.
func (t Ticks) Less(i, j int) bool {
return t[i].Value < t[j].Value
}

View File

@ -1,17 +1,13 @@
package chart
import (
"fmt"
"time"
"github.com/blendlabs/go-util"
)
import "time"
// TimeSeries is a line on a chart.
type TimeSeries struct {
Name string
Style Style
FinalValueLabel Style
Name string
Style Style
YAxis YAxisType
XValues []time.Time
YValues []float64
@ -32,6 +28,11 @@ func (ts TimeSeries) Len() int {
return len(ts.XValues)
}
// GetYAxis returns which YAxis the series draws on.
func (ts TimeSeries) GetYAxis() YAxisType {
return ts.YAxis
}
// GetValue gets a value at a given index.
func (ts TimeSeries) GetValue(index int) (x float64, y float64) {
x = float64(ts.XValues[index].Unix())
@ -39,28 +40,8 @@ func (ts TimeSeries) GetValue(index int) (x float64, y float64) {
return
}
// GetXFormatter returns the x value formatter.
func (ts TimeSeries) GetXFormatter() Formatter {
return func(v interface{}) string {
if typed, isTyped := v.(time.Time); isTyped {
return typed.Format(DefaultDateFormat)
}
if typed, isTyped := v.(int64); isTyped {
return time.Unix(typed, 0).Format(DefaultDateFormat)
}
if typed, isTyped := v.(float64); isTyped {
return time.Unix(int64(typed), 0).Format(DefaultDateFormat)
}
return util.StringEmpty
}
}
// GetYFormatter returns the y value formatter.
func (ts TimeSeries) GetYFormatter() Formatter {
return func(v interface{}) string {
if typed, isTyped := v.(float64); isTyped {
return fmt.Sprintf("%0.2f", typed)
}
return util.StringEmpty
}
// Render renders the series.
func (ts TimeSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) {
style := ts.Style.WithDefaultsFrom(defaults)
DrawLineSeries(r, canvasBox, xrange, yrange, style, ts)
}

View File

@ -55,6 +55,10 @@ func Slices(count int, total float64) []float64 {
return values
}
func flf(v float64) string {
return fmt.Sprintf("%.2f", v)
// Float is an alias for float64 that provides a better .String() method.
type Float float64
// String returns the string representation of a float.
func (f Float) String() string {
return fmt.Sprintf("%.2f", f)
}

43
value_formatter.go Normal file
View File

@ -0,0 +1,43 @@
package chart
import (
"fmt"
"time"
"github.com/blendlabs/go-util"
)
// ValueFormatter is a function that takes a value and produces a string.
type ValueFormatter func(v interface{}) string
// TimeValueFormatter is a ValueFormatter for timestamps.
func TimeValueFormatter(v interface{}) string {
return TimeValueFormatterWithFormat(v, DefaultDateFormat)
}
// TimeValueFormatterWithFormat is a ValueFormatter for timestamps with a given format.
func TimeValueFormatterWithFormat(v interface{}, dateFormat string) string {
if typed, isTyped := v.(time.Time); isTyped {
return typed.Format(dateFormat)
}
if typed, isTyped := v.(int64); isTyped {
return time.Unix(typed, 0).Format(dateFormat)
}
if typed, isTyped := v.(float64); isTyped {
return time.Unix(int64(typed), 0).Format(dateFormat)
}
return util.StringEmpty
}
// FloatValueFormatter is a ValueFormatter for float64.
func FloatValueFormatter(v interface{}) string {
return FloatValueFormatterWithFormat(v, "%.2f")
}
// FloatValueFormatterWithFormat is a ValueFormatter for float64 with a given format.
func FloatValueFormatterWithFormat(v interface{}, floatFormat string) string {
if typed, isTyped := v.(float64); isTyped {
return fmt.Sprintf(floatFormat, typed)
}
return util.StringEmpty
}

7
value_provider.go Normal file
View File

@ -0,0 +1,7 @@
package chart
// ValueProvider is a type that produces values.
type ValueProvider interface {
Len() int
GetValue(index int) (float64, float64)
}

View File

@ -36,6 +36,11 @@ type vectorRenderer struct {
fc *font.Drawer
}
// GetDPI returns the dpi.
func (vr *vectorRenderer) GetDPI() float64 {
return vr.dpi
}
// SetDPI implements the interface method.
func (vr *vectorRenderer) SetDPI(dpi float64) {
vr.dpi = dpi

27
xaxis.go Normal file
View File

@ -0,0 +1,27 @@
package chart
import "github.com/wcharczuk/go-chart/drawing"
// XAxis represents the horizontal axis.
type XAxis struct {
axis
}
// Render renders the axis
func (xa XAxis) Render(r Renderer, canvasBox Box, ra Range) {
tickFontSize := xa.Style.GetFontSize(DefaultFontSize)
tickHeight := drawing.PointsToPixels(r.GetDPI(), tickFontSize)
ty := canvasBox.Bottom + DefaultXAxisMargin + int(tickHeight)
r.SetFontColor(xa.Style.GetFontColor(DefaultAxisColor))
r.SetFontSize(tickFontSize)
ticks := xa.getTicks(ra)
for _, t := range ticks {
v := t.Value
x := ra.Translate(v)
tx := canvasBox.Left + int(x)
r.Text(t.Label, tx, ty)
}
}

28
yaxis.go Normal file
View File

@ -0,0 +1,28 @@
package chart
// YAxis is a veritcal rule of the range.
// There can be (2) y-axes; a primary and secondary.
type YAxis struct {
axis
}
// Render renders the axis.
func (ya YAxis) Render(r Renderer, canvasBox Box, ra Range, axisType YAxisType) {
var tx int
if axisType == YAxisPrimary {
tx = canvasBox.Right + DefaultYAxisMargin
} else if axisType == YAxisSecondary {
tx = canvasBox.Left - DefaultYAxisMargin
}
r.SetFontColor(ya.Style.GetFontColor(DefaultAxisColor))
r.SetFontSize(ya.Style.GetFontSize(DefaultFontSize))
ticks := ya.getTicks(ra)
for _, t := range ticks {
v := t.Value
y := ra.Translate(v)
ty := int(y)
r.Text(t.Label, tx, ty)
}
}