go chart is a basic charting library in native golang.

Overview

go-chart

CircleCI Go Report Card

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

Master should now be on the v3.x codebase, which overhauls the api significantly. Per usual, see examples for more information.

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.

Output Examples

Spark Lines:

Single axis:

Two axis:

Other Chart Types

Pie Chart:

The code for this chart can be found in examples/pie_chart/main.go.

Stacked Bar:

The code for this chart can be found in examples/stacked_bar/main.go.

Code Examples

Actual chart configurations and examples can be found in the ./examples/ directory. They are simple CLI programs that write to output.png (they are also updated with go generate.

Usage

Everything starts with the chart.Chart object. The bare minimum to draw a chart would be the following:

import (
    ...
    "bytes"
    ...
    "github.com/wcharczuk/go-chart" //exposes "chart"
)

graph := chart.Chart{
    Series: []chart.Series{
        chart.ContinuousSeries{
            XValues: []float64{1.0, 2.0, 3.0, 4.0},
            YValues: []float64{1.0, 2.0, 3.0, 4.0},
        },
    },
}

buffer := bytes.NewBuffer([]byte{})
err := graph.Render(chart.PNG, buffer)

Explanation of the above: A chart can have many Series, a Series is a collection of things that need to be drawn according to the X range and the Y range(s).

Here, we have a single series with x range values as float64s, rendered to a PNG. Note; we can pass any type of io.Writer into Render(...), meaning that we can render the chart to a file or a resonse or anything else that implements io.Writer.

API Overview

Everything on the chart.Chart object has defaults that can be overriden. Whenever a developer sets a property on the chart object, it is to be assumed that value will be used instead of the default.

The best way to see the api in action is to look at the examples in the ./_examples/ directory.

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

Contributions are welcome though this library is in a holding pattern for the forseable future.

Issues
  • Colormap Support

    Colormap Support

    After examining current Go chart options, I find this one to be best-in-class for aesthetics and detail. For my purposes, I'm only missing one key feature: colormaps.

    Specifically, for plotting X/Y scatterplots, I have a Z axis of values associated with each X/Y point. I need that Z axis to have its values from Z-min to Z-max mapped to a color range for each point, as shown here.

    A good set of colormaps is discussed here and here. As you can see there, the viridis colormap is consistently high performing for the human eye.

    opened by drgrib 11
  • Can't create a chart of a constant function

    Can't create a chart of a constant function

    Because of the way checkRanges is implemented here: https://github.com/wcharczuk/go-chart/blob/master/chart.go#L274, one can't plot something like f(x)=3.14.

    opened by viovanov 8
  • ZValues in chart.ContinuousSeries

    ZValues in chart.ContinuousSeries

    So I was indeed able to use our features from #33 to plot my z values. But it was pretty ugly. I had to index the z value from the x and y float64 values. The only way I could see to do this was to hash x and y using sprintf("%.3f_%.3f", x, y) and map it to the z value:

    zFirst := zSequence[0]
    zMin, zMax := zFirst, zFirst
    for _, z := range zSequence[1:] {
    	if z < zMin {
    		zMin = z
    	}
    	if z > zMax {
    		zMax = z
    	}
    }
    
    getHash := func(x, y float64) string {
    	hash := sprintf("%.3f_%.3f", x, y)
    	return hash
    }
    
    zHash := map[string]float64{}
    for i, x := range xSequence {
    	y := ySequence[i]
    	z := zSequence[i]
    	hash := getHash(x, y)
    	zHash[hash] = z
    }
    
    viridisOfZ := func(xr, yr chart.Range, x, y float64) drawing.Color {
    	hash := getHash(x, y)
    	z := zHash[hash]
    	return chart.Viridis(z, zMin, zMax)
    }
    

    I think it would be much better to just add and process an optional ZValues in chart.ContinuousSeries the same way XValues and YValues are processed. Then we would need to change DotColorProvider to have tho following signature:

    type DotColorProvider func(xrange, yrange, zrange Range, x, y, z float64) drawing.Color
    

    If the ZValues are not defined, the runtime can just send this function 0 for z and have zrange be from 0 to 0.

    With this functionality added, my entire program above could be reduced to

    viridisOfZ := func(xr, yr, zr chart.Range, x, y, z float64) drawing.Color {
    	return chart.Viridis(z, zr.GetMin(), zr.GetMax())
    }
    

    I think you would have a much easier time implementing this one than I since you know the flow of the plotting section of the package.

    opened by drgrib 7
  • Program stuck while running the following code

    Program stuck while running the following code

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/wcharczuk/go-chart"
    )
    
    func drawChart() {
    	sbc := chart.BarChart{
    		Height:   512,
    		BarWidth: 60,
    		XAxis: chart.Style{
    			Show: true,
    		},
    		YAxis: chart.YAxis{
    			Style: chart.Style{
    				Show: true,
    			},
    		},
    		Bars: []chart.Value{
    			{Value: 0, Label: "Blue"},
    			{Value: 0, Label: "Green"},
    			{Value: 0, Label: "Gray"},
    			{Value: 0, Label: "Orange"},
    			{Value: 0, Label: "Test"},
    			{Value: 0, Label: "??"},
    			{Value: 0, Label: "!!"},
    		},
    	}
    
    	println("rendering")
    	err := sbc.Render(chart.PNG, os.Stdout)
    	if err != nil {
    		fmt.Printf("Error rendering chart: %v\n", err)
    	}
    }
    
    func main() {
    	drawChart()
    }
    
    opened by dcu 6
  • Adds the ability to draw an XY scatter plot.

    Adds the ability to draw an XY scatter plot.

    This PR introduces two new fields on Style: DotWidth and DotColor. It also tweaks some aspects of the raster renderer, namely the .Circle function and some of the inner workings of the drawing package.

    Important consideration; so far only Draw.LineSeries uses these new fields, support in other types of plots is ongoing.

    Also adds an example for scatter plots in _examples/scatter/main.go.

    opened by wcharczuk 5
  • Allow creation of XY scatter plots (i.e. disable line between points)

    Allow creation of XY scatter plots (i.e. disable line between points)

    I'm experimenting with go-chart to replace some python charting (matplotlib), and I need to produce an XY scatter plot with values against time (see attached as a sample).

    When I plot these series using go-chart it draws lines between the points, and I couldn't figure out how to plot points/ticks only.

    Is it possible? Is this something you're considering? How would you recommend going about this if I were to help implement it? :)

    Sample XY scatter plot

    garbage-collection-durations

    opened by mattdoran 5
  • Invert Y Axis

    Invert Y Axis

    As a user I would like to be able to invert a chart axis so that I can show values as having a low absolute value but a high relative value at the top of the graph.

    Context I'm charting rank values with 1 being the highest rank and 100 being a lower relative rank. I would like to be able to invert the Y axis so that the higher rank shows as being higher on the chart.

    opened by AndyNortrup 5
  • Custom Formatter text angle

    Custom Formatter text angle

    My custom formatter is overlapping the text so I need to either adjust the tick intervals or angle the test. I can see some references in the code to setting text angle but I can't see how it's exposed.

    What are my options here.

    Also, thanks for being responsive to my other issues :)

    opened by frasergraham 5
  • Incorrect SVG rendering of PieChart when one segment makes up >50% of pie

    Incorrect SVG rendering of PieChart when one segment makes up >50% of pie

    I've tried a few different pie charts and and it looks like when one of the segments makes up >50% of the pie that segment is drawn using 360-angle, which in the example below is the orange segment.

    This is the png version that I was expecting the svg version to look like: screenshot

    And here is a screenshot of the svg that I got: screen shot 2017-09-27 at 07 17 11

    Code Snippet:

    	palette := summaryPalette{chart.AlternateColorPalette, myOverrideColors}
    
    	pie := chart.PieChart{
    		Width:  width,
    		Height: height,
    		Values: []chart.Value{
    			{Value: notAtDepotRemaining.Value, Label: fmt.Sprintf("Remaining %.0f %s", notAtDepotRemaining.Value, notAtDepotRemaining.Unit)},
    			{Value: notAtDepotUsed.Value, Label: fmt.Sprintf("Empty %.0f %s", notAtDepotUsed.Value, notAtDepotUsed.Unit)},
    			{Value: depotUsed.Value, Label: fmt.Sprintf("Returned %.0f %s", depotUsed.Value, depotUsed.Unit)},
    			{Value: depotRemaining.Value, Label: fmt.Sprintf("Stock %.0f %s", depotRemaining.Value, depotRemaining.Unit)},
    		},
    		ColorPalette: palette,
    	}
    
            ext := path.Ext(r.URL.Path)
    	switch ext {
    	case ".png":
    		w.Header().Set("Content-Type", "image/png")
    		if err := pie.Render(chart.PNG, w); err != nil {
    			return fmt.Errorf("PNG: %s", err)
    		}
    
    	case ".svg":
    		w.Header().Set("Content-Type", "image/svg+xml")
    		if err := pie.Render(chart.SVG, w); err != nil {
    			return fmt.Errorf("SVG: %s", err)
    		}
    
    	default:
    		http.NotFound(w, r)
    	}
    
    opened by lonnc 4
  • It's possible to reduce number of labels on X Axis?

    It's possible to reduce number of labels on X Axis?

    It's possible to show less values / labels on X Axis? It would be great if it could only show minimum, maximum, the middle and maybe 1 or 2 between those.

    stats

    opened by zigazajc007 3
  • go get github.com/wcharczuk/go-chart failed

    go get github.com/wcharczuk/go-chart failed

    $ go get github.com/wcharczuk/go-chart

    github.com/wcharczuk/go-chart

    E:\Code\Go\src\github.com\wcharczuk\go-chart\vector_renderer.go:173: vr.fc.MeasureString(body).Ceil undefined (type fixed.Int26_6 has no field or method Ceil)

    intel i7 amd64 win10

    opened by hydra13142 3
  • In-memory raster renderer

    In-memory raster renderer

    Noticed while testing go-chart in a UI with fairly frequent re-render requirements: There is no in-memory renderer that would let the user simply acquire an image.Image for display purposes. Using the PNG in raster_renderer.go will incur overhead as it encodes the compressed image.

    The simple change request here adds a new utility method (InMemory()), which internally extends the existing rasterRenderer to send the generated image.Image through a callback, rather than serializing to a compressed image format.

    The setup of widgets' Render(RenderProvider, io.Writer) is a bit unwieldy here. I would further suggest splitting the .Save() from the .Render(), either explicitly (requiring the graph creator to call Save()) or perhaps by a similar callback for PNG as I use here with InMemory(). I have not looked too deeply into this yet.

    opened by ebudan 0
  • Unable to generate graph

    Unable to generate graph

    Reproduction code

    x1 := time.Now().Add(10 * time.Second)
    	x2 := time.Now().Add(15 * time.Second)
    	x3 := time.Now().Add(20 * time.Second)
    	graph := chart.Chart{
    		Series: []chart.Series{
    			chart.TimeSeries{
    				XValues: []time.Time{x1, x2, x3},
    				YValues: []float64{1.0, 1.0, 1.0},
    			},
    			chart.AnnotationSeries{
    				Annotations: []chart.Value2{
    					{XValue: chart.TimeToFloat64(x1), YValue: 1.0, Label: "first"},
    					{XValue: chart.TimeToFloat64(x2), YValue: 1.0, Label: "second"},
    					{XValue: chart.TimeToFloat64(x3), YValue: 1.0, Label: "last"},
    				},
    			},
    		},
    	}
    
    	f, _ := os.Create("output.png")
    	defer f.Close()
    	fmt.Println(graph.Render(chart.PNG, f))
    
    opened by wengooooo 0
  • Pie does not return image with value 0 input

    Pie does not return image with value 0 input

    Rendering a pie chart with the following values does not return an image at all.

    []chart.Value{{Value: 0, Label: "Critical"}}
    

    go.mod: github.com/wcharczuk/go-chart/v2 v2.1.0

    Expected result: An image with an empty pie showing (maybe a circle outline in given Style) and the Label printed on the image

    opened by martinlindhe 0
  • Legend style improvements

    Legend style improvements

    This PR builds on top of #189 and it improves some visual issues such as some poorly chosen paddings and it fixes the issue that for several legends users weren't able to provide custom paddings.

    To get a feeling how I adjusted the default paddings between vertical legend elements:

    Old: output_old

    New: output_new

    opened by d-Rickyy-b 0
  • Implement Legend with fixed length line on the left side

    Implement Legend with fixed length line on the left side

    Hey there,

    I had some issues with #185 - the line in the legend was just way too long in my charts. So I implemented a legend type that puts the line on the left hand side. That way the legend looks a lot cleaner than before for legends with (at least) one long and one short label.

    Let me know what you think about it.

    Cheers, Rico

    opened by d-Rickyy-b 0
Releases(v2.0.0-rc.3)
  • v2.0.0-rc.3(Oct 28, 2016)

    Version 2.0 brings a couple new chart types; pie charts, bar charts, stacked bar charts. It brings a bunch of utilities to help with managing sparse time ranges (i.e. Market Hours).

    Version 2.0 marks a breaking API re-organization, so some updating will be required to move from v1.x charts to v2.x charts.

    What's new in RC3?

    You can now apply a TextRotationDegrees in chart styles. This will rotate text elements. There may be a myriad of corner cases and weird situations that arise from rotating the text for large text elements. You were warned.

    Source code(tar.gz)
    Source code(zip)
  • v2.0(Nov 1, 2016)

    This marks the v2.0 release of go-chart.

    New Features:

    • API re-organization
    • New Chart types:
      • Pie chart type
      • Bar chart type
      • Stacked bar chart type
    • Style options for text rotation
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-rc.2(Aug 12, 2016)

    Version 2.0 brings a couple new chart types; pie charts, bar charts, stacked bar charts. It brings a bunch of utilities to help with managing sparse time ranges (i.e. Market Hours).

    Version 2.0 marks a breaking API re-organization, so some updating will be required to move from v1.x charts to v2.x charts.

    What's new in RC2?

    • Slight tweaking of how Gridlines are handled; they no longer have an IsVertical property, instead the orientation is inferred from what axis they are attached to.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-rc.1(Aug 7, 2016)

    Version 2.0 brings a couple new chart types; pie charts, bar charts, stacked bar charts. It brings a bunch of utilities to help with managing sparse time ranges (i.e. Market Hours).

    Version 2.0 marks a breaking API re-organization, so some updating will be required to move from v1.x charts to v2.x charts.

    Source code(tar.gz)
    Source code(zip)
Owner
Will Charczuk
How do I bio.
Will Charczuk
Data visualization with chart, Create CSV file, Read Write CSV file

Data visualization with chart, Create CSV file, Read Write CSV file, Read from json file and many more in single project ......

MD FAISAL PORAG 1 Jan 13, 2022
Stock chart + gxui

chartgxui Stock chart + gxui This application is privacy practice example and non-commercial use. It has only limited experience of dealing with marke

null 0 Feb 14, 2022
🎨 The adorable charts library for Golang

go-echarts ?? The adorable charts library for Golang. If a language can be used to build web scrapers, it definitely needs to provide a graceful data

go-echarts 4.7k Jul 1, 2022
go-echarts 🎨 The adorable charts library for Golang

go-echarts ?? The adorable charts library for Golang. If a language can be used to build web scrapers, it definitely needs to provide a graceful data

go-echarts 4.7k Jun 26, 2022
Ltree Visualizer - A golang library to visualize postgres ltree type data using DOT language and Graphviz

Ltree Visualizer A golang library to visualize postgres ltree type data using DOT language and Graphviz What is Ltree? Ltree is a data type which is u

Vasubabu Jinagam 8 Jun 12, 2022
A charts library for Golang

go-charts go-charts基于go-chart生成数据图表,无其它模块的依赖纯golang的实现,支持svg与png的输出,Apache ECharts在前端开发中得到众多开发者的认可,go-charts兼容Apache ECharts的配置参数,简单快捷的生成相似的图表(svg或png

Tree Xie 42 Jun 9, 2022
Gfx - Golang file system extension library

gfx Golang文件操作扩展库,包含工作和生活中关于文件操作的各种有用的使用方法,包括 更友好的API 文件创建 文件删除 文件复制 一切皆可配置 文件名

张川 0 Mar 10, 2022
3D Wireframe Drawing Library for Go

pinhole 3D Wireframe Drawing Library for Go Javascript Version Demo Why does this exist? I needed a CPU based 3D rendering library with a very simple

Josh Baker 540 Jun 18, 2022
fswatch, this library could help watching filesystem changes, like macOS fswatch

fswatch go library for simple UNIX file system watching fswatch provides simple UNIX file system watching in Go. It is based around the Watcher struct

hitzhangjie 0 Jan 7, 2022
Globe wireframe visualizations in Golang

globe Globe wireframe visualizations in Golang backed by pinhole. Getting Started Install globe with $ go get -u github.com/mmcloughlin/globe Start wi

Michael McLoughlin 1.6k Jun 26, 2022
🚀Statsview is a real-time Golang runtime stats visualization profiler

Statsview is a real-time Golang runtime stats visualization profiler. It is built top on another open-source project, go-echarts, which helps statsview to show its graphs on the browser.

go-echarts 486 Jun 26, 2022
A golang implementation of endlessh exporting Prometheus metrics, visualized by a Grafana dashboard.

endlessh-go A golang implementation of endlessh exporting Prometheus metrics, visualized by a Grafana dashboard. Introduction Endlessh is a great idea

Shizun Ge 57 Jun 20, 2022
Interactive dependency graph visualization tool for golang

Interactive dependency graph visualization tool for golang using the awesome cytoscape graph visualizer.

Armin Becher 5 Nov 1, 2021
go chart is a basic charting library in native golang.

go-chart Package chart is a very simple golang native charting library that supports timeseries and continuous line charts. Master should now be on th

Will Charczuk 3.5k Jun 22, 2022
HSM package provides a simple state chart library written in Go.

UML HSM HSM package provides a simple state chart library written in Go. Supported UML State Chart Features Feature Implemented Test case Simple state

Chris Castro 1 Apr 14, 2022
Find out where you fall on the Open-Source Character Alignment Chart

gitaligned Find out where you fall on the Open-Source Character Alignment Chart Binaries available in releases. If you prefer to install from source,

Patricio Whittingslow 76 Apr 29, 2022
A helm v3 plugin to adopt existing k8s resources into a new generated helm chart

helm-adopt Overview helm-adopt is a helm plugin to adopt existing k8s resources into a new generated helm chart, the idea behind the plugin was inspir

Hamza ZOUHAIR 25 Jun 24, 2022
Creates Helm chart from Kubernetes yaml

Helmify CLI that creates Helm charts from kubernetes yamls. Helmify reads a list of supported k8s objects from stdin and converts it to a helm chart.

Artem 255 Jul 4, 2022
An example microservice demo using kubernetes concepts like deployment, services, persistent volume and claims, secrets and helm chart

Docker vs Kubernetes Docker Kubernetes container tech, isolated env for apps infra management, multiple containers automated builds and deploy apps -

abhijit wakchaure 0 Dec 13, 2021
Data visualization with chart, Create CSV file, Read Write CSV file

Data visualization with chart, Create CSV file, Read Write CSV file, Read from json file and many more in single project ......

MD FAISAL PORAG 1 Jan 13, 2022
Stock chart + gxui

chartgxui Stock chart + gxui This application is privacy practice example and non-commercial use. It has only limited experience of dealing with marke

null 0 Feb 14, 2022
Katenary - Convert docker-compose to a configurable helm chart

Katenary is a tool to help transforming docker-compose files to a working Helm C

Patrice Ferlet 20 Jun 25, 2022
:exclamation:Basic Assertion Library used along side native go testing, with building blocks for custom assertions

Package assert Package assert is a Basic Assertion library used along side native go testing Installation Use go get. go get github.com/go-playground/

Go Playgound 39 Apr 17, 2022
Basic-api-with-go - A basic api with golang

I am creating my first API with GO. Install go get -u github.com/Yefhem/basic-ap

Yefhem 1 Jan 3, 2022
🔥 Golang Rest Api with basic JWT Authentication and Basic Crud Operations.

?? Golang Rest Api with basic JWT Authentication and Basic Crud Operations.

Junaid Javed 13 Jun 15, 2022
REST API made using native Golang libraries. This API resembles the basic working of Instagram.

Golang RESTful API for Instagram A Go based REST API built using native libraries. The API has been thoroughly worked through with Postman. Routes inc

Bhavya Goel 1 Mar 16, 2022
Go-basic-graphql - Basic implementation of GraphQL using Go

Go-basic-graphql - Basic implementation of GraphQL using Go

Luis Felipe Ribeiro 0 Jan 29, 2022
Go-basic-skeleton - Simple and basic skeleton for go projects

Go Bootstrap (base/skeleton) Introduction This is a repository intended to serve

Kenrique Ortega 2 Mar 16, 2022
An open-source, distributed, cloud-native CD (Continuous Delivery) product designed for developersAn open-source, distributed, cloud-native CD (Continuous Delivery) product designed for developers

Developer-oriented Continuous Delivery Product ⁣ English | 简体中文 Table of Contents Zadig Table of Contents What is Zadig Quick start How to use? How to

null 0 Oct 19, 2021