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
  • 3-axis charting?

    3-axis charting?

    opened by Xeoncross 14
  • 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
  • More examples please

    More examples please

    This is a great lib! Would love a handful of examples that demonstrate more of the functionality and how to override it.

    opened by jasonmoo 7
  • 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
  • how to do transparent background?

    how to do transparent background?

    Hello, How do I remove the white background from PNG?

    opened by k1ng440 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
  • Fix bar chart y label

    Fix bar chart y label

    This pull request fixes the following issues:

    1. YAxis Label not drawn at all for BarChart.
    2. Add support for label padding

    Instead of using BarChart.drawYAxis we can use YAxis.Render method. I am unclear why this was not used in the first place otherwise we have code duplication.

    Please note that this branch contains features of an open pull request. PM me after it is approved so I can make any required changes. After the fix we can see the label output

    code

    package main
    
    //go:generate go run main.go
    
    import (
    	"os"
    
    	"github.com/wcharczuk/go-chart/v2"
    )
    
    func main() {
    	graph := chart.BarChart{
    		Title: "Test Bar Chart",
    		Background: chart.Style{
    			Padding: chart.Box{
    				Top: 40,
    			},
    		},
    		Height:   512,
    		BarWidth: 60,
    		YAxis: chart.YAxis{
    			Name: "Label Y",
    			NameStyle: chart.Style{
    				FontSize:            14,
    				Padding:             chart.NewBox(0, 40, 20, 0),
    				TextRotationDegrees: 0,
    			},
    		},
    		Bars: []chart.Value{
    			{Value: 5.25, Label: "Blue"},
    			{Value: 4.88, Label: "Green"},
    			{Value: 4.74, Label: "Gray"},
    			{Value: 3.22, Label: "Orange"},
    			{Value: 3, Label: "Test"},
    			{Value: 2.27, Label: "??"},
    			{Value: 1, Label: "!!"},
    		},
    	}
    
    	f, _ := os.Create("output.png")
    	defer f.Close()
    	graph.Render(chart.PNG, f)
    }
    
    opened by eduardhasanaj 0
  • Series renders outside of plot area

    Series renders outside of plot area

    See here: output

    I have the Y axis set manually (0, -45), because that is what I want to show, regardless of the data potentially going outside of this range. The series should be clipped at the axis, but it is rendered below the Y axis as shown in this example.

    opened by upbeat27 0
  • Feature  How to realize up-down symmetrical histogram?

    Feature How to realize up-down symmetrical histogram?

    I want to realize the upper and lower histogram. There is a line of text in the middle. How to realize the upper and lower symmetrical histogram?

    opened by zhangxuanru 0
  • Feature  How to realize the circular pie chart?

    Feature How to realize the circular pie chart?

    I want to realize the circular pie chart, that is, the middle of the pie chart is circular and transparent. How to realize it?

    opened by zhangxuanru 1
  • Documentation doesn't use v2 import

    Documentation doesn't use v2 import

    I followed the docs and was surprised and confused when no labels showed up.

    Ends up the main document page uses the old import path. Switching to "github.com/wcharczuk/go-chart/v2" made things much easier to follow.

    opened by bcl 0
  • font: initialize default font once

    font: initialize default font once

    Before this change parallel first executions of Render would fail the -race check. GOARCH=386 or amd64 would continue working fine, but arm sometimes would freeze the first invocation (I haven't dug deep enough to obtain traces).

    Platforms tested:

    • Windows 10
    • Linux: crostini (ChromeOS)
    • Linux: raspberrypi
    # crostini
    uname -a
    Linux penguin 5.4.109-26077-g12746d86825a #1 SMP PREEMPT Mon May 17 21:44:06 PDT 2021 x86_64 GNU/Linux
    
    # raspberry pi
    Linux raspberrypi 5.10.17-v7l+ #1414 SMP Fri Apr 30 13:20:47 BST 2021 armv7l GNU/Linux
    
    opened by yarcat 0
  • Support by tdewolff/canvas

    Support by tdewolff/canvas

    Hi Will, I've added support for go-chart for the tdewolff/canvas library (see https://github.com/tdewolff/canvas). This allows rendering to a host of other targets, including PDF, EPS, SVG, OpenGL, HTMLCanvas, and Gio. Just wanted to let you know, posted it here as I was unable to find an e-mail address of you. If you're interested, we could merge efforts or mention each other in the readmes. Let me know!

    opened by tdewolff 0
  • how do I pad

    how do I pad "wide" values on x axis, like histogram charts etc?

    Hello! I'm working on candlestick diagram plug-in and things go pretty well. But I don't like the candles and volume bars crawling to the left and to the right of chart, into axes/ticks area. See attached image. What is idiomatic way to make them fit inside the chart? Canvas and YAxis style padding does not seem to work. prices

    opened by andviro 0
  • X Tick Labels overlap when minLabel's width is smaller than other labels

    X Tick Labels overlap when minLabel's width is smaller than other labels

    This chart summarises the problem. As you can see, the X-axis's auto-generated labels overlap eachother.

    image

    I believe the problem is likely caused by the tick step calculation logic in GenerateContinuousTicks. https://github.com/wcharczuk/go-chart/blob/962b9abdec2bd6557efa7de5113284e720d6dbc9/tick.go#L68-L87

    In this case, the 'minLabel' is 0. The label box's width is calculated from this value, however, later labels are much larger (eg: 100000). As a result, the distance between ticks is underestimated and the labels overlap.

    Furthermore, the DefaultMinimumTickHorizontalSpacing constant cannot be overridden to force larger gaps.

    https://github.com/wcharczuk/go-chart/blob/962b9abdec2bd6557efa7de5113284e720d6dbc9/defaults.go#L56-L57

    opened by OscarVanL 0
  • Top of LegendThin is cut off

    Top of LegendThin is cut off

    I'm trying to plot a legend on my chart.

    I can't use chart.Legend as it obscures the data. I tried using chart.LegendThin, but it seems that the top of the box is clipped off in the output image.

    Even given lots of height, the legend is still cut off.

    600x500

    image

    600x800

    Schwefel Function

    No specified dimensions / auto size

    Schwefel Function

    I tried adding background padding as you did in request_timings, but now the box occludes the chart title.

    With background padding

    image

    Any suggestions?

    Code can be seen below:

    func PlotResults(res []EvolutionResults) {
    	// Create a Chart for each of the results
    	for i:=0; i<len(res); i++ {
    		result := res[i]
    
    		// Add results to a titled chart
    		graph := chart.Chart {
    			Title: result.label,
    			Background: chart.Style{
    				Padding: chart.Box{
    					Top: 50,
    				},
    			},
    			Series: []chart.Series{
    				chart.ContinuousSeries{
    					Name: "CCGA-1",
    					XValueFormatter: chart.IntValueFormatter,
    					XValues: result.XValsCCGA,
    					YValues: result.YValsCCGA,
    				},
    				chart.ContinuousSeries{
    					Name: "Standard GA",
    					XValueFormatter: chart.IntValueFormatter,
    					XValues: result.XValsGA,
    					YValues: result.YValsGA,
    				},
    			},
    		}
    
    		// Create legend for results
    		graph.Elements = []chart.Renderable{chart.LegendThin(&graph)}
    
    		// Save charts to PNG files
    		file, _ := os.Create(fmt.Sprintf("%s.png", result.label))
    
    		graph.Width = 600
    		graph.Height = 800
    		err := graph.Render(chart.PNG, file)
    
    		if err != nil {
    			fmt.Println(err)
    		}
    	}
    }
    
    opened by OscarVanL 0
Releases(v2.0)
  • 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.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.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
🎨 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.2k Nov 30, 2021
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.2k Nov 26, 2021
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 4 Oct 8, 2021
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 526 Nov 30, 2021
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.5k Dec 6, 2021
🚀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 457 Nov 24, 2021
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 29 Nov 28, 2021
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.2k Dec 6, 2021
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 0 Nov 20, 2021
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 75 Nov 17, 2021
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 7 Nov 28, 2021
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 119 Dec 3, 2021
: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 35 Nov 22, 2021
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 3 Nov 8, 2021
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
The main goal of this code is to create a basic dnstap printing tool based on the golang-dnstap library.

dnstap-parse The main goal of this code is to create a basic dnstap printing tool based on the golang-dnstap library. The output is supposed to mimic

Patrik Lundin 1 Nov 14, 2021
Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package.

Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package. The library allows you to call Go service methods from PHP with a minimal footprint, structures and []byte support.

Spiral Scout 1.1k Nov 29, 2021
🍀 Go basic library. || Go语言基础库

Go语言基础库 工程目录说明 pkg/ ...... 源码包 |-- bininfo/ ...... 将编译时源码的git版本信息(当前commit log的sha值和commit message),编译时间,Go版本,平台打入程序中

yoko 312 Nov 30, 2021
Minimalistic library for basic matrix operations.

MATRIX Maybe a bit slow, but minimalistic library for basic matrix operations. Available functions Function signature Description Equal(a, b [][]float

Vladimir Mishakov 0 Nov 4, 2021
A library for basic image processing in Go.

Imaging Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.). All the image process

null 0 Nov 25, 2021
A library for basic image processing in Go.

Imaging Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.). All the image process

null 0 Nov 26, 2021
omniparser: a native Golang ETL streaming parser and transform library for CSV, JSON, XML, EDI, text, etc.

omniparser Omniparser is a native Golang ETL parser that ingests input data of various formats (CSV, txt, fixed length/width, XML, EDI/X12/EDIFACT, JS

JF Technology 394 Nov 27, 2021
zMemif is a native golang based library for memif to interworking with dpdk.

zMemif zMemif is a native golang based library for memif to interworking with dpdk. it can simply provide 20Mpps recv and 10Mpps xmit capability. The

Mie~~~ 16 Nov 26, 2021
Basic and Digest HTTP Authentication for golang http

HTTP Authentication implementation in Go This is an implementation of HTTP Basic and HTTP Digest authentication in Go language. It is designed as a si

Lev Shamardin 498 Nov 11, 2021
A really basic thread-safe progress bar for Golang applications

progressbar A very simple thread-safe progress bar which should work on every OS without problems. I needed a progressbar for croc and everything I tr

Zack 2.2k Nov 27, 2021
A BASIC interpreter written in golang.

05 PRINT "Index" 10 PRINT "GOBASIC!" 20 PRINT "Limitations" Arrays Line Numbers IF Statement DATA / READ Statements Builtin Functions Types 30 PRINT "

Steve Kemp 271 Nov 22, 2021
A really basic thread-safe progress bar for Golang applications

progressbar A very simple thread-safe progress bar which should work on every OS without problems. I needed a progressbar for croc and everything I tr

Zack 2.2k Nov 30, 2021
Basic command line example using golang grpc client tools

This is a basic command line interface that demonstrates using the golang GRPC API. The API is reused between dishy and the wifi router, however both

null 23 Dec 1, 2021