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)
[![License](https://img.shields.io/hexpm/l/echarts.svg)](https://github.com/Mateus-M-Reis/echarts/blob/main/LICENSE)

Apache [ECharts](https://echarts.apache.org) charts for Elixir — works in
[Livebook](https://livebook.dev) via Kino and in Phoenix LiveView.

`echarts` renders a raw [ECharts option](https://echarts.apache.org/en/option.html)
map. That keeps the full ECharts surface available: candlesticks, `dataZoom`,
financial tooltips, multiple grids, custom axes, maps, 3D and any series type
ECharts supports. The ECharts 6 bundle is vendored, so charts work offline and
do not depend on a CDN.

- **Core** — `ECharts.new/2` for raw options, with validation at the JSON
  boundary and themes
- **Express** — one-call line, bar, area, scatter, pie and candlestick charts
  from lists of maps, columnar maps or Explorer DataFrames
- **Livebook** — `ECharts.Kino.new/2`, live updates with `push/2`, browser
  events with `subscribe/3`, and a no-code SmartCell
- **Phoenix LiveView** — a function component, a JavaScript hook with live
  updates and event forwarding, an asset plug, and a static renderer
- **39 bundled chart families** covering every built-in ECharts series type,
  including the GL/3D families and the optional word cloud and liquid fill
  extensions

---

## Installation

In a Livebook notebook:

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

In a 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
```

Kino and Phoenix are optional: the core module and `ECharts.Express` work
without either dependency.

---

## Livebook

```elixir
ECharts.Kino.new(%{
  xAxis: %{type: "category", data: ["Mon", "Tue", "Wed"]},
  yAxis: %{type: "value"},
  series: [%{type: "line", data: [120, 200, 150], 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)
```

### Express API

```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()
```

Multiple `:y` columns become multiple series. Columnar maps and
`Explorer.DataFrame` values are accepted too.

### Live updates

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

for point <- stream do
  ECharts.Kino.push(chart, updated_option)
end
```

`push/2` accepts a raw option map or an `ECharts.Chart`. The chart is updated
in place; the cell is not re-evaluated.

### Events

The chart forwards the events listed in the `:events` option (by default
`"click"` and `"legendselectchanged"`). Subscribe the current process:

```elixir
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)`.

### 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.

---

## Phoenix LiveView

### 1. Serve the assets

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

The plug serves only the bundled files. Unknown paths return 404.

### 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 }
})
```

The hook loads `/echarts/echarts.min.js` on demand and falls back to jsDelivr
when the plug is not mounted; mounting the plug keeps charts offline. If your
application already exposes `window.echarts` (for example through a bundler),
the hook uses it instead.

### 3. Render a chart

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

Or import `ECharts.Phoenix.Component` and use `<.echarts ...>`.

`@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.

### 4. Handle events

The hook forwards browser events as `"echarts_event"`:

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

### Large updates

Assigning a new chart re-renders the option through the DOM differ. For large
series, push the update through a LiveView event instead:

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

### Static 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 and observes DOM insertions, so charts
rendered later still mount. It requires the asset plug.

---

## 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, for map/3D series. |
| `:functions` | `%{}` | Map of callback name to JavaScript source, referenced in the option 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 all 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 matches a dark 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
the background, text, axis and tooltip colors used by the bundled examples.

### 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 plugins

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.

---

## Gallery

![ECharts gallery](https://raw.githubusercontent.com/Mateus-M-Reis/echarts/main/docs/images/gallery-overview.png)

A few of the 39 bundled examples: line, candlestick, 3D bar and word cloud.
The gallery covers every built-in 2D chart family, maps, matrix, the GL/3D
families and the optional extensions.

Open [examples/gallery.livemd](examples/gallery.livemd) in Livebook from a
checkout to render all of them.

---

## 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 ECharts bundle lives in `priv/static/echarts.min.js` (Apache 2.0). The
client entrypoints are `echarts_kino.js`, `echarts_hook.js` and
`echarts_static.js`; the shared rendering logic is `echarts_client.js`.

## License

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