ApexCharts JavaScript Chart Library

repository·main·Indexed 12 days ago

https://github.com/apexcharts/apexcharts.js

A modern, interactive JavaScript charting library for dashboards and data-heavy UIs. Version 6.8.0 supports server-side rendering (SSR), canvas rendering for dense series, and tree-shaking via apexcharts/core to reduce bundle size. Features include a plugin platform, real-time streaming, scrollytelling, and crossfilter dashboards. Provides a comprehensive API for managing chart instances, including updateOptions(), updateSeries(), and appendData().

Tokens
15.9K
Snippets
53
Records
68
Agent score
97%

What's inside ApexCharts

  1. New features in ApexCharts v6

    main

    Version 6 introduces several opt-in, tree-shakeable features that transform charts from static images into interactive surfaces:

    • Plugin platform: Use ApexCharts.registerPlugin(def) and activate via plugins: [{ name }].
    • Canvas rendering: Use chart: { renderer: 'auto' } to paint dense series to canvas while keeping UI elements in SVG.
    • Undo/Redo: Enable via chart: { history: { enabled: true } }.
    • Shareable view state: Use chart.perspectives.capture() to serialize view state into a token.
    • Design tokens: Use --apx-* CSS properties and theme: { follow: 'os' } for OS-aware themes.
    • Custom series types: Register new types via ApexCharts.registerSeriesType(name, { renderItem }).
    • Crossfilter dashboards: Link charts using ApexCharts.crossfilter.
    • Annotation authoring: Enable via chart: { ink: { enabled: true } } for draggable/resizable annotations.
    • Real-time streaming: Use chart.streaming for constant-velocity rolling-window updates.
    • Scrollytelling: Use chart.storyboard.bind({ beats }) to link prose to chart views.
  2. Understand the generated code manifest

    main

    For every generated HTML sample, the generator also produces a <sample>.code.json manifest. This manifest is used by the ApexCharts website to render idiomatic source-code tabs.

    Key characteristics of the manifest code:

    • Idiomatic Version: It uses proper npm imports for React/Vue and a clean three-file structure for Vanilla JS.
    • Cleaned Runtime: It excludes runtime glue used for the demo environment, such as the Math.random shim, license injection, and iframe resize scripts.
    • Asset Referencing: Local assets are referenced using public URLs (https://apexcharts.com/samples/assets/) so the code remains functional when copied outside the website.
  3. Configure the XML sample template

    main

    When defining a sample in XML, you can use several optional tags to control the output.

    Core Structure

    • <chart>: Defines an individual chart. A sample can contain multiple charts.
      • <id>: An optional unique identifier (number or variable-like name). Defaults to a 0-based index.
      • <options>: The configuration object passed to ApexCharts. Note: Do not surround this with curly braces {}. chart.type is mandatory. chart.height and chart.width are extracted via regex for code generation.
      • <series>: The data series array.

    Styling and Scripts

    • <title>: The sample title.
    • <style>: Custom CSS. If omitted, the default style is applied: #chart { max-width: 650px; margin: 35px auto; }.
    • <scripts>: External scripts or stylesheets required by the sample.

    Framework-Specific Customization

    To add logic specific to a framework, use the following tags:

    • Vanilla JS: Use <vanilla-js-script>. Chart instances are accessible as chart, chart{index}, or chart{id}.
    • React: Use <react-state> for additional state properties and <react-script> for component methods.
    • Vue: Use <vue-data> for data properties and <vue-script> for component methods and instance options.

    HTML Templating

    • <html ext>: An optional Nunjucks template. If omitted, it defaults to {{ charts[0] }}. The template must render a single root element. It accepts two variables:
      • format: 'vanilla-js', 'react', or 'vue'.
      • charts: An object to access format-specific HTML. Charts can be accessed by index or by their id attribute.
  4. Optimize bundle size with Tree-shaking

    main

    To reduce bundle size, instead of importing the full library with import ApexCharts from 'apexcharts', import from apexcharts/core. You must then explicitly import the chart types and features you intend to use. This can reduce typical bundles by 30-60%.

    import ApexCharts from 'apexcharts/core'   // bare class: no chart types, no features
    
    // Chart types
    import 'apexcharts/line'
    import 'apexcharts/bar'
    // import 'apexcharts/area'
    // import 'apexcharts/scatter'
    // import 'apexcharts/unit'         // dot / pictogram / waffle / beeswarm (premium)
    
    // Optional features
    import 'apexcharts/features/legend'
    import 'apexcharts/features/toolbar'      // zoom/pan toolbar
    // import 'apexcharts/features/exports'      // SVG/PNG/CSV download
    // import 'apexcharts/features/annotations' 
    // import 'apexcharts/features/keyboard'    
    // import 'apexcharts/features/drilldown'    
    // import 'apexcharts/features/morph'       
    // import 'apexcharts/features/history'     // undo/redo (premium)
    // import 'apexcharts/features/perspectives' // shareable view state (premium)
    // import 'apexcharts/features/storyboard' // scrollytelling (premium)
    // import 'apexcharts/features/facet'       // design tokens + OS themes
    // import 'apexcharts/features/weave'      // plugin platform
    // import 'apexcharts/features/marks'     // custom series types
    // import 'apexcharts/features/link'       // crossfilter / linked views (premium)
    // import 'apexcharts/features/ink'        // on-chart annotation editing (premium)
    // import 'apexcharts/features/measure'    // measure/delta ruler (premium)
    // import 'apexcharts/features/context-menu' // right-click context menu (premium)
    // import 'apexcharts/features/renderer-canvas' // canvas series renderer
  5. Generate ApexCharts samples from XML

    main

    ApexCharts uses an XML-based format to generate runnable code samples for multiple frameworks (Vanilla JS, React, and Vue). To create a new sample, start by copying template.xml.

    To build the samples from the source repository, use the following command:

    npm run build:samples

    Note that if you provide framework-specific code sections (like <react-script>), the generator will only produce HTML files for the frameworks that have custom code defined.

  6. Quick start with ApexCharts

    main

    To create a basic chart, import the ApexCharts class, instantiate it with a target DOM element and an options object, and then call the .render() method. The options object typically includes chart (type, etc.), series (data), and axis configurations like xaxis.

    import ApexCharts from 'apexcharts'
    
    const chart = new ApexCharts(document.querySelector('#chart'), {
      chart: { type: 'bar' },
      series: [{ name: 'Sales', data: [30, 40, 35, 50, 49, 60, 70, 91, 125] }],
      xaxis: { categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999] }
    })
    
    chart.render()
  7. Implement Server-Side Rendering (SSR) with ApexCharts

    main

    ApexCharts supports rendering real SVG on the server and hydrating on the client, which is compatible with frameworks like Next.js, Nuxt, SvelteKit, and Astro.

    1. On the Server: Use apexcharts/ssr to call renderToHTML. This returns hydration-ready HTML with embedded SVG.
    2. On the Client: Use apexcharts/client to call hydrate() on the specific chart element or hydrateAll() to hydrate all charts on the page.
    // Server
    import ApexCharts from 'apexcharts/ssr'
    
    const chartHTML = await ApexCharts.renderToHTML({
      chart: { type: 'bar' },
      series: [{ data: [30, 40, 35, 50, 49, 60, 70, 91, 125] }],
      xaxis: { categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999] }
    }, { width: 500, height: 300 })
    
    // Client
    import ApexCharts from 'apexcharts/client'
    
    ApexCharts.hydrate(document.getElementById('my-chart'))
    // or: ApexCharts.hydrateAll()
  8. Use the Drilldown feature for hierarchical data

    main

    The Drilldown feature allows users to navigate through levels of data. It can be configured via the drilldown option in your chart config.

    Key Capabilities:

    • Inline Series: Define child levels directly in the drilldown.series array.
    • Async Resolver: Use onDrillDown to fetch new data from an API when a user clicks a drillable point.
    • Navigation: Use drillDown(id), drillUp(), or drillToRoot() to navigate the hierarchy.
    • Caching: Enable cache: true to prevent re-fetching data when navigating back to previously visited levels.
    // Example of an async drilldown resolver
    const options = {
      drilldown: {
        enabled: true,
        onDrillDown: async (ctx) => {
          const response = await fetch(`/api/data/${ctx.id}`);
          const newData = await response.json();
          return { series: newData };
        }
      }
    };
  9. Implement custom series types with Marks API

    main

    ApexCharts allows you to define custom series types using registerSeriesType. You provide a renderItem function that receives an ApexMarksItemContext. This context gives you access to:

    • api: An ApexMarksAPI to draw primitives like path, line, rect, circle, and text.
    • scales: ApexMarksScales to map data values to pixel coordinates (e.g., api.scales.x(value)).
    • datum: The raw data object for the current point.
    • color: The series palette color.

    This is ideal for creating non-standard visualizations like custom glyphs or specialized shapes that still benefit from ApexCharts' axes and tooltips.

    // Registering a custom series type
    ApexCharts.registerSeriesType('myCustomType', {
      renderItem: (ctx) => {
        const x = ctx.scales.x(ctx.datum.x);
        const y = ctx.scales.y(ctx.datum.y);
        ctx.api.circle({ cx: x, cy: y, r: 5, fill: ctx.color });
      },
      dataType: 'xy'
    });
  10. Access stable chart state with getState()

    main

    While the internal w object contains runtime state, it is an unstable internal surface. For reliable access to the current chart state (like series names, colors, axis bounds, or dimensions) in formatters or event handlers, use the getState() method. It returns a typed ApexCharts.ChartState object.

    const state = chart.getState();
    console.log(state.seriesNames);
    console.log(state.gridWidth);
  11. Manage linked views and crossfiltering

    main

    ApexCharts supports linked views where selecting or filtering data in one chart updates others in the same group.

    • static crossfilter(opts): Creates a crossfilter coordinator. Requires the link feature. opts should include { id: string, records?: any[] }.
    • static getCrossfilter(id): Retrieves an existing coordinator by ID.
    • clearCrossfilter(): Clears crossfilter dimming for the current chart and its group.
    • getSyncedCharts(): Returns all charts in the same chart.group (including this instance).
    • getGroupedCharts(): Returns all charts in the same chart.group (excluding this instance).