go-charts

repository·main·Indexed 43 days ago

https://github.com/vicanso/go-charts

A Go library for simple and efficient chart generation supporting SVG and PNG formats. It provides compatibility with Apache ECharts configurations and supports various chart types including line, bar, horizontal bar, pie, radar, funnel, and tables. Features include multiple themes (light, dark, grafana, ant) and the ability to render ECharts option JSON strings directly to PNG.

Tokens
24.5K
Snippets
98
Records
113
Agent score
52%

What's inside go-charts

  1. Overview of go-charts

    main

    go-charts is a Go library for generating charts, based on go-chart. It provides a simpler way to generate various chart types and supports both svg and png formats.

    Key features include:

    • Supported Formats: svg and png (default is png).
    • Themes: light (default), dark, grafana, and ant.
    • ECharts Compatibility: Supports Apache ECharts options, allowing developers to generate charts using ECharts-style configurations.
    • Supported Chart Types: line, bar, horizontal bar, pie, radar, funnel, and table.
  2. How ECharts series data is handled

    main

    The library provides specialized types to handle the flexible data formats used by ECharts.

    • EChartsSeriesData: Represents a single data point in a series. It can be a simple numeric value or an object containing name, value, and itemStyle.
    • EChartsSeriesDataValue: Handles the value field, which in ECharts can be a single number or an array of numbers (e.g., for radar or funnel charts).
    • EChartsSeries: Defines the configuration for a chart series, including type (e.g., 'bar', 'line', 'pie'), radius, and markPoint/markLine annotations.
    type EChartsSeriesData struct {
    	Value     EChartsSeriesDataValue `json:"value"` 
    	Name      string                 `json:"name"` 
    	ItemStyle EChartStyle            `json:"itemStyle"` 
    }
    
    type EChartsSeries struct {
    	Data       []EChartsSeriesData `json:"data"` 
    	Name       string              `json:"name"` 
    	Type       string              `json:"type"` 
    	Radius     string              `json:"radius"` 
    	YAxisIndex int                 `json:"yAxisIndex"` 
    	ItemStyle  EChartStyle         `json:"itemStyle"` 
    	Label      EChartsLabelOption  `json:"label"` 
    	MarkPoint  EChartsMarkPoint    `json:"markPoint"` 
    	MarkLine   EChartsMarkLine     `json:"markLine"` 
    	Max        *float64            `json:"max"` 
    	Min        *float64            `json:"min"` 
    }
  3. Fill the area under a line chart

    main

    To create an area chart effect using the line chart constructor, set the FillArea field to true in your LineChartOption. You can also control the transparency of the fill using the Opacity field (a uint8 value).

    If Opacity is set to 0, the chart uses a default opacity of 200.

    opt := LineChartOption{
        FillArea: true,
        Opacity:  128, // Semi-transparent fill
        // ... other options
    }
  4. Format axis labels using Formatter

    main

    The Formatter field in AxisOption allows you to inject custom text into your axis labels. The library performs a string replacement on the Data slice, replacing every instance of the literal {value} with the corresponding data string.

    Example: If Data is []string{"10", "20"} and Formatter is "$ {value}", the rendered labels will be "$ 10" and "$ 20".

  5. Configure Bar Chart dimensions and styling

    main

    You can control the visual density and shape of the bars using BarWidth, BarMargin, and the RoundRadius property within the series data.

    • Bar Width & Margin: Use BarWidth and BarMargin in the BarChartOption to override automatic spacing calculations.
    • Rounded Bars: Within each series in the SeriesList, you can set RoundRadius. If RoundRadius > 0, the bars will be rendered as rounded rectangles instead of standard rectangles.
    • Custom Colors: Individual data items can override the series color using item.Style.FillColor.
  6. Configure chart options using OptionFunc

    main

    The go-charts library uses a functional options pattern to configure charts. Most chart rendering functions (like LineRender, BarRender, etc.) accept a variadic list of OptionFunc arguments. You can use built-in option functions to customize the chart's appearance, axes, title, and more.

    Commonly used OptionFunc providers include:

    • Output Type: SVGTypeOption(), PNGTypeOption()
    • Styling: ThemeOptionFunc(theme string), BackgroundColorOptionFunc(color Color), FontFamilyOptionFunc(fontFamily string)
    • Dimensions: WidthOptionFunc(width int), HeightOptionFunc(height int), PaddingOptionFunc(padding Box)
    • Title: TitleOptionFunc(title TitleOption), TitleTextOptionFunc(text string, subtext ...string)
    • Axes: XAxisOptionFunc(xAxisOption XAxisOption), XAxisDataOptionFunc(data []string, boundaryGap ...*bool), YAxisOptionFunc(yAxisOption ...YAxisOption), YAxisDataOptionFunc(data []string)
    • Legend: LegendOptionFunc(legend LegendOption), LegendLabelsOptionFunc(labels []string, left ...string)
    • Series Specifics: MarkLineOptionFunc(seriesIndex int, markLineTypes ...string), MarkPointOptionFunc(seriesIndex int, markPointTypes ...string)
    // Example of using functional options to configure a line chart
    LineRender(values, 
        TitleTextOptionFunc("Monthly Sales", "2023 Data"),
        WidthOptionFunc(800),
        HeightOptionFunc(400),
        ThemeOptionFunc("dark"),
        XAxisDataOptionFunc([]string{"Jan", "Feb", "Mar"}),
    )
  7. Show or hide line symbols

    main

    By default, line charts may show symbols (dots) at each data point. You can control this behavior using the SymbolShow field in LineChartOption. Because this field is a pointer to a boolean (*bool), you must pass the address of a boolean value.

    • To show symbols: Pass a pointer to true.
    • To hide symbols: Pass a pointer to false.
    // Example of hiding symbols
    showSymbols := false
    opt := LineChartOption{
        SymbolShow: &showSymbols,
        // ... other options
    }
  8. Generate a Line Chart

    main

    Use charts.LineRender to create a line chart. You provide a 2D slice of float64 values representing the series data and use option functions to configure the title, X-axis data, and legend.

    package main
    
    import (
    	charts "github.com/vicanso/go-charts/v2"
    )
    
    func main() {
    	values := [][]float64{
    		{
    			120,
    			132,
    			101,
    			134,
    			90,
    			230,
    			210,
    		},
    		// ... other series
    	}
    	p, err := charts.LineRender(
    		values,
    		charts.TitleTextOptionFunc("Line"),
    		charts.XAxisDataOptionFunc([]string{
    			"Mon",
    			"Tue",
    			"Wed",
    			"Thu",
    			"Fri",
    			"Sat",
    			"Sun",
    		}),
    		charts.LegendLabelsOptionFunc([]string{
    			"Email",
    			"Union Ads",
    			"Video Ads",
    			"Direct",
    			"Search Engine",
    		}, charts.PositionCenter),
    	)
    
    	if err != nil {
    		panic(err)
    	}
    
    	buf, err := p.Bytes()
    	if err != nil {
    		panic(err)
    	}
    	// Use buf...
    }
  9. Generate a Radar Chart

    main

    Use charts.RadarRender to create radar charts. You must provide RadarIndicatorOptionFunc to define the dimensions (indicators) and their maximum values.

    package main
    
    import (
    	"github.com/vicanso/go-charts/v2"
    )
    
    func main() {
    	values := [][]float64{
    		{
    			4200, 3000, 20000, 35000, 50000, 18000,
    		},
    		// ... other series
    	}
    	p, err := charts.RadarRender(
    		values,
    		charts.TitleTextOptionFunc("Basic Radar Chart"),
    		charts.LegendLabelsOptionFunc([]string{"Allocated Budget", "Actual Spending"}),
    		charts.RadarIndicatorOptionFunc([]string{
    			"Sales", "Administration", "Information Technology",
    			"Customer Support", "Development", "Marketing",
    		}, []float64{
    			6500, 16000, 30000, 38000, 52000, 25000,
    		}),
    	)
    	if err != nil {
    		panic(err)
    	}
    
    	buf, err := p.Bytes()
    	if err != nil {
    		panic(err)
    	}
    }
  10. Generate a Horizontal Bar Chart

    main

    Use charts.HorizontalBarRender to create a bar chart where bars are oriented horizontally. This is useful for long category names on the Y-axis.

    package main
    
    import (
    	"github.com/vicanso/go-charts/v2"
    )
    
    func main() {
    	values := [][]float64{
    		{
    			18203, 23489, 29034, 104970, 131744, 630230,
    		},
    		// ... other series
    	}
    	p, err := charts.HorizontalBarRender(
    		values,
    		charts.TitleTextOptionFunc("World Population"),
    		charts.PaddingOptionFunc(charts.Box{
    			Top:    20,
    			Right:  40,
    			Bottom: 20,
    			Left:   20,
    		}),
    		charts.LegendLabelsOptionFunc([]string{"2011", "2012"}),
    		charts.YAxisDataOptionFunc([]string{
    			"Brazil", "Indonesia", "USA", "India", "China", "World",
    		}),
    	)
    	if err != nil {
    		panic(err)
    	}
    
    	buf, err := p.Bytes()
    	if err != nil {
    		panic(err)
    	}
    }
  11. Generate a Funnel Chart

    main

    Use charts.FunnelRender to create funnel charts from a slice of float64 values.

    package main
    
    import (
    	"github.com/vicanso/go-charts/v2"
    )
    
    func main() {
    	values := []float64{100, 80, 60, 40, 20}
    	p, err := charts.FunnelRender(
    		values,
    		charts.TitleTextOptionFunc("Funnel"),
    		charts.LegendLabelsOptionFunc([]string{
    			"Show", "Click", "Visit", "Inquiry", "Order",
    		}),
    	)
    	if err != nil {
    		panic(err)
    	}
    
    	buf, err := p.Bytes()
    	if err != nil {
    		panic(err)
    	}
    }
  12. Generate a Pie Chart

    main

    Use charts.PieRender for single-series pie charts. You can configure the title, padding, legend, and show labels using option functions.

    package main
    
    import (
    	"github.com/vicanso/go-charts/v2"
    )
    
    func main() {
    	values := []float64{1048, 735, 580, 484, 300}
    	p, err := charts.PieRender(
    		values,
    		charts.TitleOptionFunc(charts.TitleOption{
    			Text:    "Rainfall vs Evaporation",
    			Subtext: "Fake Data",
    			Left:    charts.PositionCenter,
    		}),
    		charts.PaddingOptionFunc(charts.Box{
    			Top:    20,
    			Right:  20,
    			Bottom: 20,
    			Left:   20,
    		}),
    		charts.LegendOptionFunc(charts.LegendOption{
    			Orient: charts.OrientVertical,
    			Data: []string{
    				"Search Engine",
    				"Direct",
    				"Email",
    				"Union Ads",
    				"Video Ads",
    			},
    			Left: charts.PositionLeft,
    		}),
    		charts.PieSeriesShowLabel(),
    	)
    	if err != nil {
    		panic(err)
    	}
    
    	buf, err := p.Bytes()
    	if err != nil {
    		panic(err)
    	}
    }