Search code examples
pythonhtmldashboardinteractive

Export HTML for offline use (Pyecharts, Python)


Let's say I am trying to export the following chart below:

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

def create_bar_chart():
    x_data = ["A", "B", "C", "D", "E"]
    y_data = [10, 20, 30, 40, 50]
    bar = (
        Bar()
        .add_xaxis(x_data)
        .add_yaxis("Series A", y_data)
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar Chart Example"))
    )

    return bar

The problem is that I can't export the file for offline use (without internet connection). Please offer some advice. Thanks


Solution

  • You can save it as html like this:

    chart = create_bar_chart()
    chart.render("bar_chart.html")
    

    This will create a local HTML file bar_chart.html that will display your chart. However, since this relies on external (online) javascript, if you don't have internet when you use your browser to open this HTML file, it will not display as desired.

    If you peek inside the generated HTML file, you'll see that in the header, it loads in the following javascript file:

    <script type="text/javascript" 
      src="https://assets.pyecharts.org/assets/v5/echarts.min.js">
    </script>
    

    In a pinch, you can download this javascript and store it locally, say at some place on your machine local/path/to/echarts.min.js, if you need a fully offline version. Then just edit the HTML to replace the above snippet with the following:

    <script type="text/javascript" 
      src="local/path/to/echarts.min.js">
    </script>
    

    (Also consider, as an alternative to downloading a JS file: cache it, using a service worker)