# pyecharts Tutorial: Apache ECharts in Python

> A pyecharts tutorial: create ECharts bar, line, pie and calendar heatmap charts in Python, switch the interface to English, add themes and JsCode formatters, and save HTML.

Source: https://www.pythoncharts.com/python/pyecharts-echarts-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Python | Tags: pyecharts, echarts, interactive charts, javascript

pyecharts builds [Apache ECharts](https://echarts.apache.org/) charts from Python. Create a chart object such as `Bar()`, add data with `add_xaxis()` and `add_yaxis()`, set options with `set_global_opts()`, and call `render("chart.html")`. This post uses pyecharts 2.1; install it with `pip install pyecharts`.

## Quick Example

Monthly loaves sold by a sample bakery, with a toolbar that switches between bars and lines.

```python
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.globals import CurrentConfig

CurrentConfig.LOCALE = "EN"  # the built-in interface text defaults to Chinese

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sourdough = [820, 790, 905, 960, 1040, 1105]
rye = [430, 465, 440, 420, 395, 370]

chart = (
    Bar(init_opts=opts.InitOpts(width="100%", height="420px"))
    .add_xaxis(months)
    .add_yaxis("Sourdough", sourdough, color="#b5651d")
    .add_yaxis("Rye", rye, color="#5c4033")
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Loaves sold", pos_left="left"),
        legend_opts=opts.LegendOpts(pos_top="40px"),
        tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="shadow"),
        toolbox_opts=opts.ToolboxOpts(
            pos_left="right",
            feature={"magicType": {"type": ["line", "bar", "stack"]},
                     "restore": {}, "saveAsImage": {}}),
    )
)
chart.render("loaves.html")
```

![pyecharts grouped bar chart of loaves sold from January to June; sourdough rises from 820 to 1105 and rye falls to 370](https://www.pythoncharts.com/python/pyecharts-echarts-python/images/pyecharts-quick-example.png)

Sourdough sales rise from 820 to 1,105 loaves while rye drifts down to 370. Hover for values, click a legend entry to hide a series, and use the icons at the top right to switch chart type or download a PNG.

## Why Is My pyecharts Toolbar in Chinese?

pyecharts creates charts with the `ZH` locale. Set `CurrentConfig.LOCALE = "EN"` before creating any chart, and the toolbox hints and other built-in text appear in English. Your titles and data are unaffected.

## How a pyecharts Chart Is Put Together

| Call | Sets |
|---|---|
| `Bar(init_opts=...)` | Size, theme and renderer |
| `add_xaxis()`, `add_yaxis()` | The data, as plain Python lists |
| `set_series_opts()` | Options for the series: labels, mark lines |
| `set_global_opts()` | Title, legend, axes, tooltip, toolbox, zoom |
| `render()` | Writes an HTML file |

Each method returns the chart, which is why they chain.

Convert NumPy arrays and pandas columns with `.tolist()`. `list(array)` isn't enough: it keeps NumPy integer types, which pyecharts 2.1 writes as `null`, so the series comes out empty with no error.

## Line Chart With Zoom and Mark Lines

`DataZoomOpts` adds a draggable range slider. `MarkPointOpts` and `MarkLineOpts` label the maximum and average without computing them yourself.

```python
import numpy as np
import pandas as pd
from pyecharts.charts import Line

rng = np.random.default_rng(5)
days = pd.date_range("2026-01-01", periods=150)
visitors = (220 + np.linspace(0, 140, 150) + 60 * (days.dayofweek >= 5)
            + rng.normal(0, 22, 150)).round()

chart = (
    Line(init_opts=opts.InitOpts(width="100%", height="420px"))
    .add_xaxis(days.strftime("%b %d").tolist())
    .add_yaxis("Visitors", visitors.tolist(), is_symbol_show=False, color="#0b7285",
               areastyle_opts=opts.AreaStyleOpts(opacity=0.15))
    .set_series_opts(
        markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
        markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Daily shop visitors"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        legend_opts=opts.LegendOpts(is_show=False),
        datazoom_opts=[opts.DataZoomOpts(range_start=40, range_end=100),
                       opts.DataZoomOpts(type_="inside")],
    )
)
chart.render("visitors.html")
```

![ECharts area line chart of daily shop visitors with a range slider, a maximum marker and a dashed average line](https://www.pythoncharts.com/python/pyecharts-echarts-python/images/pyecharts-line-zoom.png)

Drag the slider handles or scroll over the chart to change the window. The average line and the maximum marker are computed from all the data.

## Donut Chart

A `Pie` takes `(name, value)` pairs. Two radius values make a donut, and `{b}`, `{c}` and `{d}` in a label formatter stand for the name, value and percentage.

```python
from pyecharts.charts import Pie

channels = [("Counter", 5120), ("Online", 2380), ("Wholesale", 1760), ("Market stall", 940)]

chart = (
    Pie(init_opts=opts.InitOpts(width="100%", height="400px"))
    .add("Loaves", channels, radius=["45%", "70%"],
         label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
    .set_colors(["#b5651d", "#2b8a3e", "#1864ab", "#e67700"])
    .set_global_opts(title_opts=opts.TitleOpts(title="Sales by channel"),
                     legend_opts=opts.LegendOpts(pos_bottom="0"))
)
chart.render("channels.html")
```

![Donut chart of sales by channel: counter is the largest at about half, followed by online, wholesale and the market stall](https://www.pythoncharts.com/python/pyecharts-echarts-python/images/pyecharts-donut.png)

## Calendar Heatmap

`Calendar` draws a GitHub-style grid from `[date, value]` pairs.

```python
from pyecharts.charts import Calendar

dates = pd.date_range("2026-01-01", "2026-12-31")
orders = (rng.poisson(14, len(dates)) + 9 * (dates.dayofweek >= 4)
          + 8 * (dates.month == 12))
pairs = [[d.strftime("%Y-%m-%d"), int(v)] for d, v in zip(dates, orders)]

chart = (
    Calendar(init_opts=opts.InitOpts(width="100%", height="230px"))
    .add("Orders", pairs, calendar_opts=opts.CalendarOpts(
        range_="2026", pos_left="40", pos_right="10", pos_top="60", cell_size=["auto", 16],
        yearlabel_opts=opts.CalendarYearLabelOpts(is_show=False)))
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Online orders per day, 2026"),
        visualmap_opts=opts.VisualMapOpts(
            min_=int(orders.min()), max_=int(orders.max()), orient="horizontal",
            pos_left="center", pos_bottom="0",
            range_color=["#fff4e6", "#ffa94d", "#a8380b"]),
        legend_opts=opts.LegendOpts(is_show=False),
    )
)
chart.render("calendar.html")
```

![Calendar heatmap of online orders for each day of 2026, darker on Fridays to Sundays and in December](https://www.pythoncharts.com/python/pyecharts-echarts-python/images/pyecharts-calendar.png)

Fridays to Sundays and December are darker. For a static version, see the [calendar heatmap in Matplotlib and Plotly](https://www.pythoncharts.com/python/github-contribution-heatmap-python/).

## Themes and JavaScript Formatters

Pick a theme with `InitOpts(theme=...)`. When a format string isn't enough, `JsCode` passes a JavaScript function through to ECharts.

```python
from pyecharts.commons.utils import JsCode
from pyecharts.globals import ThemeType

shops = ["Harbor", "Campus", "Station", "Old Town", "Airport"]
revenue = [48200, 39500, 61800, 27400, 55100]

chart = (
    Bar(init_opts=opts.InitOpts(width="100%", height="380px", theme=ThemeType.MACARONS))
    .add_xaxis(shops[::-1])
    .add_yaxis("Revenue", revenue[::-1])
    .reversal_axis()
    .set_series_opts(label_opts=opts.LabelOpts(
        position="right",
        formatter=JsCode("function (p) { return '$' + (p.value / 1000).toFixed(1) + 'k'; }")))
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Revenue by shop"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
            formatter=JsCode("function (v) { return '$' + v / 1000 + 'k'; }")), max_=70000),
        yaxis_opts=opts.AxisOpts(axisline_opts=opts.AxisLineOpts(is_show=False)),
        legend_opts=opts.LegendOpts(is_show=False),
    )
)
chart.render("revenue.html")
```

![Horizontal bar chart of revenue by shop with dollar labels; Station is highest at 61.8k and Old Town lowest at 27.4k](https://www.pythoncharts.com/python/pyecharts-echarts-python/images/pyecharts-theme-jscode.png)

`reversal_axis()` turns the bars horizontal. The label formatter receives a parameter object, while the axis formatter receives the tick value.

## Show Charts in Jupyter or Save Them

In classic Notebook-style front ends, `chart.render_notebook()` returns an object that displays under the cell. JupyterLab needs the notebook type set first, then the JavaScript loaded in its own cell:

```python
from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB  # set before importing charts

from pyecharts.charts import Bar
Bar().load_javascript()

# next cell
Bar().add_xaxis(["a", "b"]).add_yaxis("n", [1, 2]).render_notebook()
```

| Output | Method |
|---|---|
| A complete HTML file | `chart.render("chart.html")` |
| An HTML string | `chart.render_embed()` |
| The ECharts option object | `chart.dump_options()` |
| Several charts on one page | `Page().add(chart1, chart2).render("page.html")` |
| A PNG from Python | `make_snapshot()` with the extra `snapshot-selenium` package and a browser driver |

## Why Is My pyecharts Chart Blank?

The saved HTML loads ECharts from `assets.pyecharts.org`, so it needs an internet connection. When I tested in November 2026, some requests to that server failed with an expired certificate, which leaves an empty page and a script error in the browser console. Point pyecharts at another copy of ECharts with `ONLINE_HOST`, set before you create the chart:

```python
CurrentConfig.ONLINE_HOST = "https://cdn.jsdelivr.net/npm/echarts@6.0.0/dist/"
```

This folder has `echarts.min.js` but not pyecharts' `themes/` folder, so it works for charts using the default or `dark` theme. For other themes, host the pyecharts asset files yourself and point `ONLINE_HOST` at them.

## When Should I Use pyecharts?

pyecharts suits dashboards and web pages where you want ECharts' animations and chart types such as calendar, liquid fill and word cloud. [Plotly](https://www.pythoncharts.com/plotly/plotly-tutorial/) is easier if your data lives in DataFrames, and its English documentation is more complete; much of the pyecharts documentation is in Chinese. The [library comparison](https://www.pythoncharts.com/python/python-interactive-charting-libraries-compared/) shows the same chart in both.

## Similar Topics

- [Embedding Interactive Charts in a Website](https://www.pythoncharts.com/python/embed-interactive-charts-website/)
- [D3.js Charts From Python](https://www.pythoncharts.com/python/d3-from-python/)
- [Pie and Donut Charts in Plotly](https://www.pythoncharts.com/plotly/plotly-pie-charts-donut-charts/)
