chartjs

package module
v0.0.0-...-a37b166 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2017 License: MIT Imports: 7 Imported by: 13

README

chartjs

go wrapper for chartjs

GoDoc Build Status

Chartjs charts are defined purely in JSON, so this library is mostly structs and struct-tags that dictate how to marshal to JSON. None of the currently implemented parts are stringly-typed in this library so it can avoid many errors.

The chartjs javascript/JSON api has a lot of surface area. Currently, only the options that I use are provided. More can and will be added as I need them (or via pull-requests).

There is a small amount of code to simplify creating charts.

data to be plotted by chartjs has to meet this interface.

  type Values interface {
      // X-axis values. If only these are specified then it must be a Bar plot.
      Xs() []float64
      // Optional Y values.
      Ys() []float64
      // Rs are used to size points for chartType `Bubble`. If this returns an
      // empty slice then it's not used.
      Rs() []float64
  }

Example

This longish example shows common use of the library.

package main

import (
	"log"
	"math"
	"os"

	chartjs "github.com/brentp/go-chartjs"
)

// satisfy the required interface with this struct and methods.
type xy struct {
	x []float64
	y []float64
	r []float64
}

func (v xy) Xs() []float64 {
	return v.x
}
func (v xy) Ys() []float64 {
	return v.y
}
func (v xy) Rs() []float64 {
	return v.r
}

func check(e error) {
	if e != nil {
		log.Fatal(e)
	}
}

func main() {
	var xys1 xy
	var xys2 xy

    // make some example data.
	for i := float64(0); i < 9; i += 0.1 {
		xys1.x = append(xys1.x, i)
		xys2.x = append(xys2.x, i)

		xys1.y = append(xys1.y, math.Sin(i))
		xys2.y = append(xys2.y, 3*math.Cos(2*i))

	}

	// a set of colors to work with.
	colors := []*types.RGBA{
		&types.RGBA{102, 194, 165, 220},
		&types.RGBA{250, 141, 98, 220},
		&types.RGBA{141, 159, 202, 220},
		&types.RGBA{230, 138, 195, 220},
	}

	// a Dataset contains the data and styling info.
	d1 := chartjs.Dataset{Data: xys1, BorderColor: colors[1], Label: "sin(x)", Fill: chartjs.False,
		PointRadius: 10, PointBorderWidth: 4, BackgroundColor: colors[0]}

	d2 := chartjs.Dataset{Data: xys2, BorderWidth: 8, BorderColor: colors[3], Label: "3*cos(2*x)",
		Fill: chartjs.False, PointStyle: chartjs.Star}

	chart := chartjs.Chart{Label: "test-chart"}

	var err error
	_, err = chart.AddXAxis(chartjs.Axis{Type: chartjs.Linear, Position: chartjs.Bottom, ScaleLabel: &chartjs.ScaleLabel{FontSize: 22, LabelString: "X", Display: chartjs.True}})
	check(err)
	d1.YAxisID, err = chart.AddYAxis(chartjs.Axis{Type: chartjs.Linear, Position: chartjs.Left,
		ScaleLabel: &chartjs.ScaleLabel{LabelString: "sin(x)", Display: chartjs.True}})
	check(err)
	chart.AddDataset(d1)

	d2.YAxisID, err = chart.AddYAxis(chartjs.Axis{Type: chartjs.Linear, Position: chartjs.Right,
		ScaleLabel: &chartjs.ScaleLabel{LabelString: "3*cos(2*x)", Display: chartjs.True}})
	check(err)
	chart.AddDataset(d2)

	chart.Options.Responsive = chartjs.False

	wtr, err := os.Create("example-chartjs-multi.html")
	if err != nil {
	}
	if err := chart.SaveHTML(wtr, nil); err != nil {
		log.Fatal(err)
	}
	wtr.Close()
}

The resulting html will have an interactive <canvas> element that looks like this.

plot

Live Examples

evaluating coverage on high throughput sequencing data

inferring sex from sequencing coverage on X and Y chroms

Documentation

Overview

Package chartjs simplifies making chartjs.org plots in go.

Index

Constants

View Source
const (
	// Line is a "line" plot
	Line chartType = iota
	// Bar is a "bar" plot
	Bar
	// Bubble is a "bubble" plot
	Bubble
)
View Source
const (
	InterpMonotone interpMode
	InterpDefault
)
View Source
const (
	Circle
	Triangle
	Rect
	RectRot
	Cross
	CrossRot
	Star
	LinePoint
	Dash
)
View Source
const (
	// Category is a categorical axis (this is the default),
	// used for bar plots.
	Category axisType = iota
	// Linear axis should be use for scatter plots.
	Linear
	// Log axis
	Log
	// Time axis
	Time
	// Radial axis
	Radial
)
View Source
const (
	// Bottom puts the axis on the bottom (used for Y-axis)
	Bottom axisPosition = iota + 1
	// Top puts the axis on the bottom (used for Y-axis)
	Top
	// Left puts the axis on the bottom (used for X-axis)
	Left
	// Right puts the axis on the bottom (used for X-axis)
	Right
)

Variables

View Source
var ChartJS = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"

ChartJS holds the path to hosted ChartJS

View Source
var False = types.False
View Source
var JQuery = "https://code.jquery.com/jquery-2.2.4.min.js"

JQuery holds the path to hosted JQuery

View Source
var True = types.True
View Source
var XFloatFormat = "%.2f"

XFloatFormat determines how many decimal places are sent in the JSON for X values.

View Source
var YFloatFormat = "%.2f"

YFloatFormat determines how many decimal places are sent in the JSON for Y values.

Functions

func SaveCharts

func SaveCharts(w io.Writer, tmap map[string]interface{}, charts ...Chart) error

SaveCharts writes the charts and the required HTML to an io.Writer

Types

type Axes

type Axes struct {
	XAxes []Axis `json:"xAxes,omitempty"`
	YAxes []Axis `json:"yAxes,omitempty"`
}

Axes holds the X and Y axies. Its simpler to use Chart.AddXAxis, Chart.AddYAxis.

func (*Axes) AddX

func (a *Axes) AddX(x Axis)

AddX adds a X-Axis.

func (*Axes) AddY

func (a *Axes) AddY(y Axis)

AddY adds a Y-Axis.

type Axis

type Axis struct {
	Type      axisType     `json:"type"`
	Position  axisPosition `json:"position,omitempty"`
	Label     string       `json:"label,omitempty"`
	ID        string       `json:"id,omitempty"`
	GridLines types.Bool   `json:"gridLine,omitempty"`
	Stacked   types.Bool   `json:"stacked,omitempty"`

	// Bool differentiates between false and empty by use of pointer.
	Display    types.Bool  `json:"display,omitempty"`
	ScaleLabel *ScaleLabel `json:"scaleLabel,omitempty"`
	Tick       *Tick       `json:"ticks,omitempty"`
}

Axis corresponds to 'scale' in chart.js lingo.

type Chart

type Chart struct {
	Type    chartType `json:"type"`
	Label   string    `json:"label,omitempty"`
	Data    Data      `json:"data,omitempty"`
	Options Options   `json:"options,omitempty"`
}

Chart is the top-level type from chartjs.

func (*Chart) AddDataset

func (c *Chart) AddDataset(d Dataset)

AddDataset adds a dataset to the chart.

func (*Chart) AddXAxis

func (c *Chart) AddXAxis(x Axis) (string, error)

AddXAxis adds an x-axis to the chart and returns the ID of the added axis.

func (*Chart) AddYAxis

func (c *Chart) AddYAxis(y Axis) (string, error)

AddYAxis adds an y-axis to the chart and return the ID of the added axis.

func (Chart) SaveHTML

func (c Chart) SaveHTML(w io.Writer, tmap map[string]interface{}) error

SaveHTML writes the chart and minimal HTML to an io.Writer.

type Data

type Data struct {
	Datasets []Dataset `json:"datasets"`
	Labels   []string  `json:"labels"`
}

Data wraps the "data" JSON

type Dataset

type Dataset struct {
	Data            Values      `json:"-"`
	Type            chartType   `json:"type,omitempty"`
	BackgroundColor *types.RGBA `json:"backgroundColor,omitempty"`
	// BorderColor is the color of the line.
	BorderColor *types.RGBA `json:"borderColor,omitempty"`
	// BorderWidth is the width of the line.
	BorderWidth float64 `json:"borderWidth"`

	// Label indicates the name of the dataset to be shown in the legend.
	Label string     `json:"label,omitempty"`
	Fill  types.Bool `json:"fill,omitempty"`

	// SteppedLine of true means dont interpolate and ignore line tension.
	SteppedLine            types.Bool  `json:"steppedLine,omitempty"`
	LineTension            float64     `json:"lineTension"`
	CubicInterpolationMode interpMode  `json:"cubicInterpolationMode,omitempty"`
	PointBackgroundColor   *types.RGBA `json:"pointBackgroundColor,omitempty"`
	PointBorderColor       *types.RGBA `json:"pointBorderColor,omitempty"`
	PointBorderWidth       float64     `json:"pointBorderWidth"`
	PointRadius            float64     `json:"pointRadius"`
	PointHitRadius         float64     `json:"pointHitRadius"`
	PointHoverRadius       float64     `json:"pointHoverRadius"`
	PointHoverBorderColor  *types.RGBA `json:"pointHoverBorderColor,omitempty"`
	PointHoverBorderWidth  float64     `json:"pointHoverBorderWidth"`
	PointStyle             shape       `json:"pointStyle,omitempty"`

	ShowLine types.Bool `json:"showLine,omitempty"`
	SpanGaps types.Bool `json:"spanGaps,omitempty"`

	// Axis ID that matches the ID on the Axis where this dataset is to be drawn.
	XAxisID string `json:"xAxisID,omitempty"`
	YAxisID string `json:"yAxisID,omitempty"`

	// set the formatter for the data, e.g. "%.2f"
	// these are not exported in the json, just used to determine the decimals of precision to show
	XFloatFormat string `json:"-"`
	YFloatFormat string `json:"-"`
}

Dataset wraps the "dataset" JSON

func (Dataset) MarshalJSON

func (d Dataset) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

type Legend

type Legend struct {
	Display types.Bool `json:"display,omitempty"`
}

type Option

type Option struct {
	Responsive          types.Bool `json:"responsive,omitempty"`
	MaintainAspectRatio types.Bool `json:"maintainAspectRatio,omitempty"`
	Title               *Title     `json:"title,omitempty"`
}

Option wraps the chartjs "option"

type Options

type Options struct {
	Option
	Scales  Axes     `json:"scales,omitempty"`
	Legend  *Legend  `json:"legend,omitempty"`
	Tooltip *Tooltip `json:"tooltips,omitempty"`
}

Options wraps the chartjs "options"

type ScaleLabel

type ScaleLabel struct {
	Display     types.Bool  `json:"display,omitempty"`
	LabelString string      `json:"labelString,omitempty"`
	FontColor   *types.RGBA `json:"fontColor,omitempty"`
	FontFamily  string      `json:"fontFamily,omitempty"`
	FontSize    int         `json:"fontSize,omitempty"`
	FontStyle   string      `json:"fontStyle,omitempty"`
}

ScaleLabel corresponds to scale title. Display: True must be specified for this to be shown.

type Tick

type Tick struct {
	Min         float64    `json:"min,omitempty"`
	Max         float64    `json:"max,omitempty"`
	BeginAtZero types.Bool `json:"beginAtZero,omitempty"`
}

Tick lets us set the range of the data.

type Title

type Title struct {
	Display types.Bool `json:"display,omitempty"`
	Text    string     `json:"text,omitempty"`
}

Title is the Options title

type Tooltip

type Tooltip struct {
	Enabled   types.Bool `json:"enabled,omitempty"`
	Intersect types.Bool `json:"intersect,omitempty"`
	// TODO: make mode typed by Interaction modes.
	Mode   string         `json:"mode,omitempty"`
	Custom template.JSStr `json:"custom,omitempty"`
}

Tooltip wraps chartjs "tooltips". TODO: figure out how to make this work.

type Values

type Values interface {
	// X-axis values. If only these are specified then it must be a Bar plot.
	Xs() []float64
	// Optional Y values.
	Ys() []float64
	// Rs are used to size points for chartType `Bubble`
	Rs() []float64
}

Values dictates the interface of data to be plotted.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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