# How to Embed Interactive Python Charts in a Website

> Embed interactive Python charts in a website: use Plotly to_html(), Altair to_html(), Bokeh components() and ECharts options as HTML fragments, or load saved charts in iframes.

Source: https://www.pythoncharts.com/python/embed-interactive-charts-website/ | Published: 2026-11-27 | Author: Alex Scott | Category: Python | Tags: embed, html, plotly, altair, bokeh, pyecharts, interactive charts

To embed an interactive Python chart in a web page, export it as an HTML fragment (a `<div>` plus the scripts that draw into it) and paste that into your page. In Plotly the call is `fig.to_html(full_html=False, include_plotlyjs="cdn")`. Altair, Bokeh and pyecharts have their own versions, shown below. The charts then work on any static host, with no Python server.

## Quick Example

This writes `report.html`, an ordinary web page with a live Plotly chart in the middle.

```python
from pathlib import Path

import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(23)
loans = pd.DataFrame({
    "month": pd.date_range("2025-01-01", periods=18, freq="MS").repeat(2),
    "format": ["Print", "E-book"] * 18,
})
base = np.where(loans["format"] == "Print", 5200 - loans.index * 22, 2100 + loans.index * 68)
loans["loans"] = (base + rng.normal(0, 190, len(loans))).round()

fig = px.line(loans, x="month", y="loans", color="format", markers=True,
              color_discrete_map={"Print": "#364fc7", "E-book": "#e8590c"},
              labels={"month": "", "loans": "Loans", "format": ""},
              title="Library loans by format", template="plotly_white")
fig.update_layout(height=400, margin=dict(l=50, r=20, t=60, b=30))

fragment = fig.to_html(full_html=False, include_plotlyjs="cdn", div_id="loans-chart")

page = f"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Library report</title></head>
<body style="max-width:700px; margin:auto; font-family:sans-serif">
<h1>Library report</h1>
<p>E-book loans are catching up with print.</p>
{fragment}
</body>
</html>"""
Path("report.html").write_text(page, encoding="utf-8")
```

<div style="height:400px; width:100%;">                        </div>
![Plotly line chart of monthly library loans in which print falls and e-books rise](https://www.pythoncharts.com/python/embed-interactive-charts-website/images/embed-plotly-fragment.png)

The chart above is that fragment, pasted into this page. Print loans drift down over the 18 months while e-book loans nearly double.

## Plotly: to_html()

| Argument | Effect |
|---|---|
| `full_html=False` | Returns only the `<div>` and scripts |
| `include_plotlyjs="cdn"` | Adds a script tag that loads plotly.js from Plotly's CDN |
| `include_plotlyjs=False` | Adds no loader, for the second and later charts on a page |
| `include_plotlyjs=True` | Pastes the whole library into the fragment, several megabytes |
| `div_id="loans-chart"` | Sets a stable id in place of a random one |
| `config={"displayModeBar": False}` | Hides the toolbar |

See [saving Plotly figures as standalone HTML](https://www.pythoncharts.com/plotly/plotly-saving-standalone-html-files/) for more on file output.

## Altair: to_html(fullhtml=False)

Give each chart its own `output_div`. The default id is `vis`, so two charts with the default would fight over the same element.

```python
import altair as alt

totals = loans.groupby("format", as_index=False)["loans"].sum()
chart = alt.Chart(totals).mark_bar().encode(
    x=alt.X("loans:Q", title="Total loans"),
    y=alt.Y("format:N", title=None),
    color=alt.Color("format:N", legend=None,
                    scale=alt.Scale(domain=["Print", "E-book"],
                                    range=["#364fc7", "#e8590c"])),
    tooltip=["format:N", alt.Tooltip("loans:Q", format=",")],
).properties(width="container", height=120)

altair_fragment = chart.to_html(fullhtml=False, output_div="totals-chart")
```

  <style>
    #totals-chart.vega-embed {
      width: 100%;
      display: flex;
    }
    #totals-chart.vega-embed details,
    #totals-chart.vega-embed details summary {
      position: relative;
    }
  </style>
  <div id="totals-chart"></div>
![Altair horizontal bar chart of total print and e-book loans, with print higher](https://www.pythoncharts.com/python/embed-interactive-charts-website/images/embed-altair-fragment.png)

The fragment loads Vega, Vega-Lite and Vega-Embed from jsDelivr. `width="container"` makes the chart follow the width of the page.

## Bokeh: components()

`components()` returns the script and the `<div>` separately. The page also needs BokehJS, from the same Bokeh version that made the chart.

```python
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.resources import Resources

print_loans = loans[loans["format"] == "Print"]
p = figure(x_axis_type="datetime", height=300, sizing_mode="stretch_width",
           title="Print loans")
p.line(print_loans["month"], print_loans["loans"], line_width=3, color="#364fc7")

script, div = components(p)
loader = Resources(mode="cdn", components=["bokeh"]).render()
bokeh_fragment = loader + div + script
```

Add `"bokeh-widgets"` to `components` if the layout has sliders or other widgets, and `"bokeh-tables"` for data tables. For charts loaded by your own JavaScript, `bokeh.embed.json_item()` returns JSON that `Bokeh.embed.embed_item()` draws.

## pyecharts: Build the Div and Script

`render_embed()` returns a complete HTML document. For a fragment, write the element yourself and pass in the chart's options.

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

yearly = loans.groupby([loans["month"].dt.year, "format"])["loans"].sum()
bar = (Bar()
       .add_xaxis(["2025", "2026 (Jan-Jun)"])
       .add_yaxis("Print", [int(yearly[y, "Print"]) for y in (2025, 2026)])
       .add_yaxis("E-book", [int(yearly[y, "E-book"]) for y in (2025, 2026)])
       .set_global_opts(title_opts=opts.TitleOpts(title="Loans per year")))

echarts_fragment = f"""
<div id="yearly-chart" style="width:100%; height:360px"></div>
"""
```

## Put Several Libraries on One Page

Fragments from different libraries can share a page, as long as every element id is unique.

```python
sections = [fragment, altair_fragment, bokeh_fragment, echarts_fragment]
body = "\n<hr>\n".join(sections)
dashboard = f"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Library dashboard</title></head>
<body style="max-width:700px; margin:auto">
{body}
</body>
</html>"""
Path("dashboard.html").write_text(dashboard, encoding="utf-8")
```

![One web page showing a Plotly line chart, an Altair bar chart, a Bokeh line chart and an ECharts bar chart of library loans](https://www.pythoncharts.com/python/embed-interactive-charts-website/images/embed-dashboard.png)

## Use an iframe Instead

Save the chart as its own file and point an `iframe` at it. The chart's CSS and JavaScript stay separate from your page, which helps when a site builder or content system interferes with scripts.

```python
fig.write_html("loans.html", include_plotlyjs="cdn")

iframe = ('<iframe src="loans.html" title="Library loans by format" '
          'width="100%" height="420" style="border:0" loading="lazy"></iframe>')
```

| | HTML fragment | iframe |
|---|---|---|
| Library loaded | Once per page | Once per iframe |
| Page styles can affect the chart | Yes | No |
| Height | Follows the chart | Fixed by you |
| Files to publish | The page | The page and one file per chart |
| Best for | Your own site or generator | Content systems and untrusted styling |

An iframe only isolates a page you trust. Don't embed HTML from someone else without the `sandbox` attribute.

## Embed Charts in Markdown and Static Site Generators

Pelican, Hugo, Jekyll and MkDocs can pass raw HTML through Markdown, with settings that differ between them. Check these when a chart doesn't appear:

- **Blank lines.** Many Markdown parsers end a raw HTML block at a blank line and format the rest as text. Strip them: `"\n".join(line for line in fragment.splitlines() if line.strip())`.
- **Raw HTML disabled.** Hugo omits it by default; set `markup.goldmark.renderer.unsafe` to `true`, or put the fragment in a shortcode.
- **Template syntax.** If your generator treats `{{ }}` as template code, wrap the fragment in that engine's raw block.
- **Duplicate libraries.** Load each JavaScript library once, with the version that matches the Python package that created the chart.

This site uses that approach: a script writes each chart's fragment into the Markdown file, alongside a static PNG for readers without JavaScript.

## How Heavy Are Embedded Charts?

The data travels inside the fragment, so size grows with the number of points. For the small charts above, each fragment is a few kilobytes plus the shared library, which the browser downloads once and caches. Aggregate large datasets before plotting, or [render them as an image](https://www.pythoncharts.com/python/datashader-millions-points/). The charts are also public: anyone who can load the page can read the data in its source.

## Similar Topics

- [Python Interactive Charting Libraries Compared](https://www.pythoncharts.com/python/python-interactive-charting-libraries-compared/)
- [Saving Altair Charts as HTML, PNG and SVG](https://www.pythoncharts.com/altair/save-altair-charts/)
- [D3.js Charts From Python](https://www.pythoncharts.com/python/d3-from-python/)
- [Bokeh Tutorial](https://www.pythoncharts.com/bokeh/bokeh-tutorial/)
