Packages

Apache ECharts charts for Elixir, Livebook and Phoenix LiveView

Current section

Files

Jump to
echarts README.md
Raw

README.md

# ECharts

[![Hex.pm](https://img.shields.io/hexpm/v/echarts.svg)](https://hex.pm/packages/echarts)
[![HexDocs](https://img.shields.io/badge/hex-docs-lightgreen.svg)](https://hexdocs.pm/echarts)
[![CI](https://github.com/Mateus-M-Reis/echarts/actions/workflows/ci.yml/badge.svg)](https://github.com/Mateus-M-Reis/echarts/actions/workflows/ci.yml)
[![License](https://img.shields.io/hexpm/l/echarts.svg)](https://hex.pm/packages/echarts)
[![Apache ECharts 6.1](https://img.shields.io/badge/ECharts-6.1-aa344d)](https://echarts.apache.org)

Apache [ECharts](https://echarts.apache.org) charts for Elixir — raw option
maps, one-call Express builders, **Livebook** via Kino, **Phoenix LiveView**,
and static HTML.

The ECharts 6 bundle is vendored, so charts work offline and do not depend on
a CDN. If the Phoenix asset plug is not mounted, the client falls back to
jsDelivr.

![ECharts gallery](docs/images/gallery-overview.png)

*A few of the 39 bundled charts: line, candlestick, 3D bar and word cloud.*

---

## Why ECharts?

ECharts is a full charting system, not a grammar of graphics. Keeping the raw
option map available means you get:

- **Financial charts that behave** — candlesticks, `dataZoom`, crosshairs,
  multi-grid volume panels and financial tooltips without a translation layer.
- **Every series type** — line, bar, scatter, heatmap, sankey, sunburst,
  graph, tree, treemap, theme river, parallel, matrix, maps, 3D.
- **Real interactivity** — zoom, brush, legend toggles, tooltips, linked
  grids and event subscriptions.
- **No network at runtime** — the bundle and the optional GL/wordcloud/liquid
  fill extensions ship in `priv/static`.

`echarts` validates only the boundaries it owns (the option is a map, the
rendering options are valid) and leaves the option internals to ECharts. New
series types work without a package release.

## What you get

| Layer | Module | Works in |
|---|---|---|
| Core chart + validation | `ECharts`, `ECharts.Chart` | any Elixir app |
| Concise builders | `ECharts.Express` | any Elixir app |
| Livebook kino | `ECharts.Kino` | Livebook |
| No-code cell | `ECharts.Kino.SmartCell` | Livebook |
| LiveView component | `ECharts.Phoenix.Component` | Phoenix LiveView |
| Static renderer | `static_echarts/2` | Phoenix controllers |
| Asset server | `ECharts.Phoenix.Plug` | Phoenix / Plug |

Kino and Phoenix are optional dependencies: the core and Express layers work
without either.

### Requirements

- Elixir 1.15 or later.
- Kino 0.19+ for the Livebook integration.
- Phoenix LiveView 1.0+ for the component and hook.
- A modern browser with `ResizeObserver`; WebGL for `gl: true` charts.

---

## Installation

### Livebook

```elixir
Mix.install([
  {:echarts, "~> 0.1"},
  {:kino, "~> 0.19"}
])
```

### Mix project

```elixir
def deps do
  [
    {:echarts, "~> 0.1"},
    # Optional integrations:
    {:kino, "~> 0.19", optional: true},              # Livebook
    {:phoenix_live_view, "~> 1.0", optional: true},  # LiveView
    {:plug, "~> 1.0", optional: true}                # asset plug
  ]
end
```

---

## Quick start

### Livebook: raw option

```elixir
ECharts.Kino.new(%{
  xAxis: %{type: "category", data: ["Mon", "Tue", "Wed", "Thu", "Fri"]},
  yAxis: %{type: "value"},
  series: [
    %{type: "line", data: [120, 200, 150, 80, 170], smooth: true}
  ]
})
```

Use `ECharts.Kino.render/2` when you do not need to keep the kino around:

```elixir
ECharts.Kino.render(option, height: 360, theme: :dark)
```

### Livebook: Express

```elixir
data = [
  %{"month" => "Jan", "sales" => 42},
  %{"month" => "Feb", "sales" => 55},
  %{"month" => "Mar", "sales" => 38}
]

ECharts.Express.bar(data, x: "month", y: "sales", title: "Monthly sales")
|> ECharts.Kino.render()
```

### Phoenix LiveView

**1. Serve the assets**

```elixir
# router.ex
forward "/echarts", ECharts.Phoenix.Plug
```

The plug serves an allowlist of bundled files with immutable caching. If it is
not mounted, the JavaScript clients fall back to jsDelivr.

**2. Register the hook**

```javascript
// assets/js/app.js
import { EChartsHook } from "../../deps/echarts/priv/static/echarts_hook.js"

let liveSocket = new LiveSocket("/live", Socket, {
  hooks: { EChartsHook }
})
```

If your application already exposes `window.echarts` (for example through a
bundler), the hook uses it instead of downloading the bundle.

**3. Render a chart**

```elixir
<ECharts.Phoenix.Component.echarts id="sales" chart={@chart} class="h-96 w-full" />
```

`@chart` is an `ECharts.Chart` or a raw option map. Assigning a new chart
updates it in place. The container uses the chart height by default; pass
`class` or `style` to size it with your own CSS.

Import `ECharts.Phoenix.Component` if you prefer the `<.echarts ...>` shorthand.

### Static HTML

For controller-rendered pages:

```elixir
# controller
render(conn, :index, chart: ECharts.Express.line(data, x: "month", y: "sales"))

# template
<%= ECharts.Phoenix.Component.static_echarts(@chart, id: "sales") %>
```

The static renderer scans the page on load and observes DOM insertions, so
charts rendered later (for example by a LiveView patch) still mount. It needs
the asset plug mounted.

See the full [Phoenix LiveView guide](guides/phoenix.md) for router, hook,
events, live updates, static pages and troubleshooting. A runnable
[Phoenix demo](https://github.com/Mateus-M-Reis/echarts/tree/main/examples/phoenix_demo) covers the same flow in a real
application, including a static page.

---

## Live updates and events

### Livebook

```elixir
chart = ECharts.Kino.new(option)

# Update the chart in place, without re-evaluating the cell
for point <- stream do
  ECharts.Kino.push(chart, updated_option)
end

# Receive browser events
ECharts.Kino.subscribe(chart, :chart_events)

receive do
  {:chart_events, %{"type" => "click", "data" => data}} ->
    IO.inspect(data)
end
```

Subscribe to one event type with `subscribe(chart, tag, :click)`, or subscribe
another process with `subscribe(chart, pid, tag)`.

### Phoenix LiveView

The hook forwards the chart's `:events` to the LiveView:

```elixir
def handle_event("echarts_event", %{"type" => type, "data" => data}, socket) do
  {:noreply, assign(socket, last_event: {type, data})}
end
```

For large series, skip the DOM differ and push the chart directly:

```elixir
def handle_event("refresh", _params, socket) do
  chart = build_chart()
  {:noreply, ECharts.Phoenix.push_update(socket, "sales", chart)}
end
```

The payload is a JSON-safe summary: `seriesIndex`, `seriesName`, `name`,
`dataIndex`, `data`, `value`, `percent`, `start`, `end`, `selected`, plus the
cursor position as `x`/`y` when available.

---

## Express API

`ECharts.Express` builds a validated `ECharts.Chart` from tabular data. It
accepts a list of maps (string or atom keys), a columnar map, or an
`Explorer.DataFrame`.

| Function | Required options | Notes |
|---|---|---|
| `line/2` | `:x`, `:y` | `:smooth`, `:area`, `:stack`, `:data_zoom` |
| `bar/2` | `:x`, `:y` | stacked and grouped bars |
| `area/2` | `:x`, `:y` | area fill under a line |
| `scatter/2` | `:x`, `:y` | numeric columns become `[x, y]` pairs |
| `pie/2` | `:name`, `:value` | `:donut`, `:rose` |
| `candlestick/2` | `:x`, `:open`, `:high`, `:low`, `:close` | optional `:volume` panel |

All builders accept `:title`, `:subtitle`, `:height`, `:theme`, `:renderer`,
`:gl`, `:plugins`, `:maps`, `:functions` and `:events`.

```elixir
ECharts.Express.candlestick(candles,
  x: "date",
  open: "open",
  high: "high",
  low: "low",
  close: "close",
  volume: "volume",
  height: 480
)
```

---

## Charts and options

```elixir
ECharts.new(option, opts)
```

| Option | Default | Description |
|---|---|---|
| `:height` | `420` | Chart height in pixels. |
| `:theme` | `nil` | `:light` (default), `:dark`, a custom theme name, or a theme map. |
| `:renderer` | `"canvas"` | `"canvas"` or `"svg"`. SVG is useful for printing and crisp screenshots. |
| `:gl` | `false` | Load `echarts-gl` for 3D series. |
| `:plugins` | `[]` | Load bundled extensions: `"wordcloud"` and/or `"liquidfill"`. |
| `:maps` | `%{}` | Map of `name => GeoJSON` registered before rendering. |
| `:functions` | `%{}` | Map of callback name to JavaScript source, referenced as `%{"$function" => "name"}`. |
| `:events` | `["click", "legendselectchanged"]` | Browser events forwarded by the integrations. `:all` forwards every name in `ECharts.Events.all/0`; `[]` disables forwarding. |

The option map can use atom or string keys. It is JSON-encoded before being
sent to the browser, so values must be JSON-encodable.

### Themes

`theme: :light` uses the ECharts default palette. `theme: :dark` uses the
built-in dark theme. For a palette that follows your application, pass a theme
map:

```elixir
ECharts.new(option, theme: ECharts.Theme.dark())
```

`ECharts.Theme.light/0` and `ECharts.Theme.dark/0` return ready-made maps with
background, text, axis and tooltip colors.

### Maps

ECharts does not bundle geographic data. Register GeoJSON before rendering:

```elixir
ECharts.new(
  %{
    series: [%{type: "map", map: "demo", data: [%{name: "Norte", value: 80}]}]
  },
  maps: %{"demo" => geo_json}
)
```

### Custom series

ECharts callbacks cannot travel as JSON. Pass their source with `:functions`
and use a marker where the function is expected:

```elixir
ECharts.new(
  %{
    series: [
      %{
        type: "custom",
        renderItem: %{"$function" => "renderItem"},
        data: [[0, 10], [1, 20]]
      }
    ]
  },
  functions: %{"renderItem" => "function (params, api) { ... }"}
)
```

Functions are compiled with `new Function` in the browser. Only pass trusted
code — the notebook or application author already runs arbitrary code.

### 3D and extensions

Pass `gl: true` for `bar3D`, `scatter3D`, `line3D`, `surface`, `globe`,
`map3D`, `lines3D`, `polygons3D`, `scatterGL`, `graphGL` and `flowGL`. The
`echarts-gl` bundle is loaded only for those charts.

Pass `plugins: ["wordcloud"]` or `plugins: ["liquidfill"]` for the bundled
extensions. `mapbox3D` and `maptalks3D` need external SDKs/tokens and are not
bundled.

---

## SmartCell

The no-code **ECharts chart** cell is registered automatically when Kino is
available. Pick a notebook variable, a chart type and the columns; the cell
generates an `ECharts.Express` call that you can copy and edit.

Supported chart types: line, bar, area, scatter, pie and candlestick.

---

## Gallery

The 39-chart gallery covers every built-in ECharts series type, including the
GL/3D families and the optional word cloud and liquid fill extensions:

- [examples/gallery.livemd](examples/gallery.livemd)
- [examples/basic.livemd](examples/basic.livemd)

Open either file in Livebook from a checkout, or browse the
[documentation](https://hexdocs.pm/echarts).

---

## How it works

```
ECharts.Chart ──► to_map/1 ──┬──► ECharts.Kino        (Kino.JS.Live)
                             ├──► ECharts.Phoenix     (data attribute + hook)
                             └──► static_echarts/2    (queue + module scan)
```

All three clients share `priv/static/echarts_client.js`, which loads the
bundles, registers maps, revives callbacks, creates the instance, handles
resize and forwards events. The bundles are versioned in the URL so the
immutable browser cache never serves an old copy after an upgrade.

## Security

Assets are public in every integration. Never put secrets (API keys, private
account data) in the option map. Treat everything passed to `ECharts.new/2` as
visible to anyone who can load the notebook output or the page.

## Development

```bash
mix deps.get
mix format --check-formatted
mix compile --warnings-as-errors
mix test
mix docs

# Browser smoke for all 39 charts (Chromium + WebGL)
mix run visual/generate.exs
cd visual && npm ci --include=dev
npx playwright install chromium
npx playwright test
```

The visual suite also covers the Phoenix hook and the static renderer.

## Related packages

- [`kino_echarts`](https://hex.pm/packages/kino_echarts) — compatibility wrapper
  for notebooks written against the 0.7 API.
- [Apache ECharts](https://echarts.apache.org) — the upstream project and
  option reference.

## License

ECharts is released under the MIT License. Apache ECharts is bundled under the
Apache License 2.0; see [NOTICE](NOTICE).