GPandas

Plotting Charts

Visualize DataFrame data with interactive bar, line, pie, scatter, histogram, and heatmap charts

Learn how to create interactive charts directly from your DataFrames using GPandas' built-in plotting capabilities, powered by go-echarts.

Overview

GPandas provides several chart types that render as interactive HTML files:

Chart TypeMethodDescription
Bar ChartPlotBar()Compare categorical data with vertical bars
Line ChartPlotLine()Visualize trends and changes over time
Pie ChartPlotPie()Show proportional distribution of categories
Scatter ChartPlotScatter()Plot one numeric column against another
HistogramPlotHistogram()Show the frequency distribution of a numeric column
HeatmapPlotHeatmap()Color a grid of numeric values (e.g. a correlation matrix)

All charts are rendered using the go-echarts library and output self-contained HTML files with interactive features like tooltips and legends.


ChartOptions

Every plot method accepts a ChartOptions struct to configure chart appearance and output.

Struct Definition

import "github.com/apoplexi24/gpandas/plot"

type ChartOptions struct {
    Title      string   // Chart title displayed at the top
    Width      int      // Chart width in pixels (default: 900)
    Height     int      // Chart height in pixels (default: 500)
    OutputPath string   // File path for HTML output (required)
    Theme      string   // Chart theme (optional, e.g., "light", "dark")
}

Fields

FieldTypeDescriptionDefault
TitlestringChart title displayed at the top"" (no title)
WidthintChart width in pixels900
HeightintChart height in pixels500
OutputPathstringFile path for the generated HTML fileRequired
ThemestringVisual theme for styling"" (go-echarts default)

Default Options

Use DefaultChartOptions() to get a pre-configured options struct:

opts := plot.DefaultChartOptions()
// Width: 900, Height: 500, Title: "", Theme: ""

// Override specific fields
opts.Title = "My Chart"
opts.OutputPath = "output/chart.html"

Bar Chart

Creates a vertical bar chart from two DataFrame columns — one for x-axis labels and one for y-axis values.

Function Signature

func (df *DataFrame) PlotBar(xCol, yCol string, opts *plot.ChartOptions) error

Parameters

ParameterTypeDescription
xColstringColumn name for x-axis labels
yColstringColumn name for y-axis values (must be numeric)
opts*plot.ChartOptionsChart configuration

Data Flow

Example

package main

import (
    "fmt"
    "log"

    "github.com/apoplexi24/gpandas"
    "github.com/apoplexi24/gpandas/plot"
)

func main() {
    gp := gpandas.GoPandas{}
    
    // Create sales DataFrame
    df, _ := gp.DataFrame(
        []string{"Month", "Revenue"},
        []gpandas.Column{
            {"Jan", "Feb", "Mar", "Apr", "May", "Jun"},
            {45230.5, 52100.75, 48900.25, 61500.0, 58700.5, 67800.25},
        },
        map[string]any{
            "Month":   gpandas.StringCol{},
            "Revenue": gpandas.FloatCol{},
        },
    )
    
    // Create bar chart
    err := df.PlotBar("Month", "Revenue", &plot.ChartOptions{
        Title:      "Monthly Sales Revenue",
        Width:      900,
        Height:     500,
        OutputPath: "output/bar_chart.html",
    })
    if err != nil {
        log.Fatalf("PlotBar failed: %v", err)
    }
    
    fmt.Println("Bar chart saved to output/bar_chart.html")
}

Output

The generated HTML file renders an interactive bar chart:


Line Chart

Creates a line chart from DataFrame columns. Supports plotting multiple series on the same chart — ideal for comparing trends.

Function Signature

func (df *DataFrame) PlotLine(xCol string, yCols []string, opts *plot.ChartOptions) error

Parameters

ParameterTypeDescription
xColstringColumn name for x-axis labels
yCols[]stringOne or more column names for y-axis values (must be numeric)
opts*plot.ChartOptionsChart configuration

Data Flow

Single Series Example

// Plot a single line
err := df.PlotLine("Month", []string{"Temperature"}, &plot.ChartOptions{
    Title:      "Monthly Temperature",
    OutputPath: "output/temperature.html",
})

Multiple Series Example

package main

import (
    "fmt"
    "log"

    "github.com/apoplexi24/gpandas"
    "github.com/apoplexi24/gpandas/plot"
)

func main() {
    gp := gpandas.GoPandas{}
    
    // Create weather DataFrame
    df, _ := gp.DataFrame(
        []string{"Month", "Temperature", "Humidity"},
        []gpandas.Column{
            {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"},
            {5.2, 7.1, 12.3, 16.8, 21.5, 25.3, 28.1, 27.4, 23.2, 17.5, 11.2, 6.8},
            {78.5, 72.3, 68.1, 65.4, 62.8, 58.2, 55.6, 57.3, 63.5, 70.2, 75.8, 80.1},
        },
        map[string]any{
            "Month":       gpandas.StringCol{},
            "Temperature": gpandas.FloatCol{},
            "Humidity":    gpandas.FloatCol{},
        },
    )
    
    // Plot multiple series on one chart
    err := df.PlotLine("Month", []string{"Temperature", "Humidity"}, &plot.ChartOptions{
        Title:      "Monthly Temperature and Humidity Trends",
        Width:      1000,
        Height:     500,
        OutputPath: "output/line_chart.html",
    })
    if err != nil {
        log.Fatalf("PlotLine failed: %v", err)
    }
    
    fmt.Println("Line chart saved to output/line_chart.html")
}

Output

The generated HTML file renders an interactive line chart with legends:


Pie Chart

Creates a pie chart showing proportional distribution. Uses one column for slice labels and another for slice values.

Function Signature

func (df *DataFrame) PlotPie(labelCol, valueCol string, opts *plot.ChartOptions) error

Parameters

ParameterTypeDescription
labelColstringColumn name for pie slice labels
valueColstringColumn name for pie slice values (must be numeric)
opts*plot.ChartOptionsChart configuration

Data Flow

Example

package main

import (
    "fmt"
    "log"

    "github.com/apoplexi24/gpandas"
    "github.com/apoplexi24/gpandas/plot"
)

func main() {
    gp := gpandas.GoPandas{}
    
    // Create product sales DataFrame
    df, _ := gp.DataFrame(
        []string{"Category", "Sales"},
        []gpandas.Column{
            {"Electronics", "Clothing", "Home & Garden", "Sports", "Books", "Toys", "Food & Beverage", "Health & Beauty"},
            {2850.0, 1920.0, 1450.0, 980.0, 720.0, 1100.0, 1680.0, 1340.0},
        },
        map[string]any{
            "Category": gpandas.StringCol{},
            "Sales":    gpandas.FloatCol{},
        },
    )
    
    // Create pie chart
    err := df.PlotPie("Category", "Sales", &plot.ChartOptions{
        Title:      "Product Category Sales Distribution",
        Width:      1000,
        Height:     600,
        OutputPath: "output/pie_chart.html",
    })
    if err != nil {
        log.Fatalf("PlotPie failed: %v", err)
    }
    
    fmt.Println("Pie chart saved to output/pie_chart.html")
}

Output

The generated HTML file renders an interactive pie chart with a vertical legend:


Data Requirements

Y-Axis / Value Columns

All plot methods require numeric columns for values:

Supported TypeGo TypeDescription
Integerint64Whole numbers, automatically converted to float64
Floatfloat64Decimal numbers

Null Value Handling

ScenarioBehavior
Null in x-axis / label columnRow is skipped
Null in y-axis / value columnRow is skipped
Both nullRow is skipped

Theming

Charts support theming via the Theme field in ChartOptions. Themes are provided by go-echarts.

// Default theme (light)
opts := &plot.ChartOptions{
    Title:      "My Chart",
    OutputPath: "chart.html",
}

// Dark theme
opts := &plot.ChartOptions{
    Title:      "My Chart",
    OutputPath: "chart.html",
    Theme:      "dark",
}

Plotting Pipeline

Combine DataFrame operations with plotting for end-to-end analysis:


Error Handling

Common Errors

ErrorCauseSolution
"DataFrame is nil"Operating on nil DataFrameCheck DataFrame initialization
"cannot plot empty DataFrame"DataFrame has no rows or columnsVerify data was loaded correctly
"column 'X' not found in DataFrame"Invalid column nameCheck column exists with df.String()
"ySeries validation failed"Value column is not numericEnsure value column is int64 or float64
"output path is required"OutputPath not set in ChartOptionsSet OutputPath in options
"failed to create output file"File system errorCheck directory exists and permissions
"yCols cannot be empty"Empty yCols slice in PlotLineProvide at least one y-axis column

Error Handling Example

err := df.PlotBar("Category", "Revenue", &plot.ChartOptions{
    Title:      "Sales Report",
    OutputPath: "output/sales.html",
})
if err != nil {
    switch {
    case strings.Contains(err.Error(), "not found"):
        log.Fatal("Column doesn't exist in DataFrame")
    case strings.Contains(err.Error(), "not numeric"):
        log.Fatal("Value column must be int64 or float64")
    case strings.Contains(err.Error(), "output path"):
        log.Fatal("Please specify an output file path")
    default:
        log.Fatalf("Plot error: %v", err)
    }
}

Complete Example: Sales Dashboard

package main

import (
    "fmt"
    "log"

    "github.com/apoplexi24/gpandas"
    "github.com/apoplexi24/gpandas/plot"
)

func main() {
    gp := gpandas.GoPandas{}
    
    // Load sales data
    sales, err := gp.Read_csv("sales_data.csv")
    if err != nil {
        log.Fatalf("Failed to load data: %v", err)
    }
    
    fmt.Println("Sales Data:")
    fmt.Println(sales.String())
    
    // 1. Bar chart: Revenue by category
    err = sales.PlotBar("Category", "Revenue", &plot.ChartOptions{
        Title:      "Revenue by Category",
        Width:      900,
        Height:     500,
        OutputPath: "output/revenue_bar.html",
    })
    if err != nil {
        log.Printf("Bar chart error: %v", err)
    }
    
    // 2. Line chart: Monthly trends
    err = sales.PlotLine("Month", []string{"Revenue", "Profit"}, &plot.ChartOptions{
        Title:      "Monthly Revenue vs Profit",
        Width:      1000,
        Height:     500,
        OutputPath: "output/trends_line.html",
    })
    if err != nil {
        log.Printf("Line chart error: %v", err)
    }
    
    // 3. Pie chart: Market share distribution
    err = sales.PlotPie("Product", "MarketShare", &plot.ChartOptions{
        Title:      "Market Share Distribution",
        Width:      1000,
        Height:     600,
        OutputPath: "output/share_pie.html",
    })
    if err != nil {
        log.Printf("Pie chart error: %v", err)
    }
    
    fmt.Println("\nDashboard charts generated in output/ directory")
}

Scatter Chart

Plots one numeric column against another. Both columns must be numeric, and rows where either value is null are skipped.

Method Signature

func (df *DataFrame) PlotScatter(xCol, yCol string, opts *plot.ChartOptions) error

Example

opts := &plot.ChartOptions{
    Title:      "Sales vs Units",
    OutputPath: "output/scatter.html",
}
err := df.PlotScatter("units", "sales", opts)
if err != nil {
    log.Fatalf("PlotScatter failed: %v", err)
}

Histogram

Bins a numeric column into equal-width intervals and plots the frequency of each bin. A non-positive bins value defaults to 10. Null values are skipped.

Method Signature

func (df *DataFrame) PlotHistogram(column string, bins int, opts *plot.ChartOptions) error

Example

opts := &plot.ChartOptions{
    Title:      "Sales Distribution",
    OutputPath: "output/histogram.html",
}
err := df.PlotHistogram("sales", 20, opts)
if err != nil {
    log.Fatalf("PlotHistogram failed: %v", err)
}

Heatmap

Renders a grid of numeric values colored by magnitude. Numeric columns form the x-axis and row index labels form the y-axis. This pairs naturally with Corr() to visualize a correlation matrix.

Method Signature

func (df *DataFrame) PlotHeatmap(opts *plot.ChartOptions) error

Example

// Visualize a correlation matrix as a heatmap
corr, err := df.Corr()
if err != nil {
    log.Fatalf("Corr failed: %v", err)
}

opts := &plot.ChartOptions{
    Title:      "Correlation Matrix",
    OutputPath: "output/heatmap.html",
}
err = corr.PlotHeatmap(opts)
if err != nil {
    log.Fatalf("PlotHeatmap failed: %v", err)
}

See Correlation, Sampling & Pipe for computing correlation matrices.


See Also

On this page