CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyecharts

Python ❤️ ECharts = pyecharts - comprehensive data visualization toolkit built on Apache ECharts

Pending
Overview
Eval results
Files

rendering.mddocs/

Rendering and Output

Chart rendering capabilities supporting multiple output formats and integration environments. pyecharts provides flexible rendering options for HTML files, static images, Jupyter notebooks, and web framework integration.

Capabilities

Chart Rendering Methods

Core rendering methods available on all chart instances.

class ChartRenderMethods:
    def render(self, path="render.html"):
        """
        Render chart to HTML file.
        
        Args:
            path (str): Output file path
            
        Returns:
            str: Generated HTML content
        """

    def render_embed(self):
        """
        Render chart as embeddable HTML fragment.
        
        Returns:
            str: HTML fragment without full page structure
        """

    def render_notebook(self):
        """
        Render chart for Jupyter notebook display.
        
        Returns:
            HTML: Jupyter notebook HTML display object
        """

    def dump_options(self):
        """
        Export chart configuration as JSON.
        
        Returns:
            str: JSON string of chart options
        """

    def dump_options_with_quotes(self):
        """
        Export chart configuration as JSON with quoted keys.
        
        Returns:
            str: JSON string with quoted keys
        """

    def get_js_dependencies(self):
        """
        Get JavaScript dependencies for the chart.
        
        Returns:
            list: List of required JavaScript files
        """

Static Image Generation

Generate static images from interactive charts using browser automation.

def make_snapshot(driver, file_content, output_name, delay=1, pixel_ratio=1, is_remove_html=False, **kwargs):
    """
    Generate static image snapshot of chart.
    
    Args:
        driver: Browser driver instance (selenium, pyppeteer, phantomjs)
        file_content (str): HTML content or file path
        output_name (str): Output image file path
        delay (int): Delay before screenshot in seconds  
        pixel_ratio (int): Device pixel ratio for high-DPI displays
        is_remove_html (bool): Remove temporary HTML file after generation
        **kwargs: Additional driver-specific options
        
    Returns:
        str: Output file path
    """

Supported Image Formats:

  • PNG (default)
  • JPEG/JPG
  • PDF (driver-dependent)
  • SVG (driver-dependent)

Usage Example:

from pyecharts.charts import Bar
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot as driver

# Create chart
bar = Bar().add_xaxis(["A", "B", "C"]).add_yaxis("Series", [1, 2, 3])

# Generate image
make_snapshot(driver, bar.render(), "chart.png")

Browser Driver Options

Different browser automation drivers for image generation.

Selenium Driver

# Install: pip install snapshot-selenium
from snapshot_selenium import snapshot as selenium_driver

make_snapshot(selenium_driver, chart.render(), "output.png", delay=2)

PyPPeteer Driver

# Install: pip install snapshot-pyppeteer
from snapshot_pyppeteer import snapshot as pyppeteer_driver

make_snapshot(pyppeteer_driver, chart.render(), "output.png")

PhantomJS Driver

# Install: pip install snapshot-phantomjs
from snapshot_phantomjs import snapshot as phantomjs_driver

make_snapshot(phantomjs_driver, chart.render(), "output.png")

Jupyter Notebook Integration

Seamless integration with Jupyter environments for interactive development.

class JupyterIntegration:
    def render_notebook(self):
        """
        Display chart in Jupyter notebook cell output.
        
        Returns:
            HTML: IPython HTML display object
        """

    def load_javascript(self):
        """
        Load required JavaScript libraries in notebook.
        
        Note: Usually handled automatically
        """

Jupyter Usage Patterns:

# Basic notebook display
from pyecharts.charts import Bar

bar = Bar().add_xaxis(["A", "B", "C"]).add_yaxis("Series", [1, 2, 3])
bar.render_notebook()  # Displays chart inline

# JupyterLab support
# Charts display natively in JupyterLab cells

# Notebook theming
from pyecharts import options as opts

bar = Bar(init_opts=opts.InitOpts(theme="dark"))
# Theme automatically adapts to notebook environment

Web Framework Integration

Integration helpers for popular Python web frameworks.

Flask Integration

from flask import Flask, render_template
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import CurrentConfig

app = Flask(__name__)

# Configure pyecharts for Flask
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))

@app.route("/")
def index():
    bar = (
        Bar()
        .add_xaxis(["A", "B", "C", "D"])
        .add_yaxis("Series", [1, 2, 3, 4])
        .set_global_opts(title_opts=opts.TitleOpts(title="Flask Chart"))
    )
    return render_template("index.html", chart=bar.render_embed())

Django Integration

from django.shortcuts import render
from pyecharts.charts import Line

def chart_view(request):
    line = (
        Line()
        .add_xaxis(["Jan", "Feb", "Mar", "Apr"])
        .add_yaxis("Revenue", [100, 200, 150, 300])
    )
    
    context = {"chart": line.render_embed()}
    return render(request, "chart.html", context)

Sanic Integration

from sanic import Sanic, response
from pyecharts.charts import Pie

app = Sanic("ChartApp")

@app.route("/chart")
async def chart_handler(request):
    pie = (
        Pie()
        .add("", [("A", 25), ("B", 35), ("C", 40)])
    )
    
    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head><title>Chart</title></head>
    <body>{pie.render_embed()}</body>
    </html>
    """
    return response.html(html_content)

Asset Management

JavaScript asset handling and CDN configuration.

# Global configuration options
class CurrentConfig:
    ONLINE_HOST = "https://assets.pyecharts.org/assets/"  # CDN host
    NOTEBOOK_TYPE = "jupyter_notebook"  # Notebook type
    
# Asset management functions
def configure_assets(host=None, **kwargs):
    """
    Configure asset loading settings.
    
    Args:
        host (str): Custom asset host URL
        **kwargs: Additional configuration options
    """

def get_js_dependencies():
    """
    Get list of JavaScript dependencies.
    
    Returns:
        list: Required JavaScript files
    """

Custom Asset Configuration:

from pyecharts.globals import CurrentConfig

# Use local assets
CurrentConfig.ONLINE_HOST = "http://localhost:8000/assets/"

# Use custom CDN
CurrentConfig.ONLINE_HOST = "https://cdn.jsdelivr.net/npm/echarts@5/dist/"

Template System

Template-based rendering for custom HTML output.

class TemplateEngine:
    def render_chart_to_file(self, chart, template_name, output_path, **context):
        """
        Render chart using custom template.
        
        Args:
            chart: Chart instance
            template_name (str): Template file name
            output_path (str): Output file path
            **context: Additional template context variables
        """

    def render_charts_to_file(self, charts, template_name, output_path, **context):
        """
        Render multiple charts using custom template.
        
        Args:
            charts (list): List of chart instances
            template_name (str): Template file name
            output_path (str): Output file path
            **context: Additional template context variables
        """

Custom Template Example:

<!-- templates/custom_chart.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
</head>
<body>
    <h1>{{ title }}</h1>
    <div id="chart" style="width: 100%; height: 400px;"></div>
    {{ chart_script }}
</body>
</html>

Performance Optimization

Rendering optimization techniques for better performance.

Lazy Loading

# Enable lazy loading for large datasets
from pyecharts import options as opts

bar = (
    Bar(init_opts=opts.InitOpts(renderer="canvas"))  # Use canvas for better performance
    .add_xaxis(large_dataset_x)
    .add_yaxis("Series", large_dataset_y, is_large=True, large_threshold=1000)
)

Progressive Enhancement

# Progressive rendering for large datasets
bar = (
    Bar()
    .add_xaxis(data_x)
    .add_yaxis("Series", data_y, progressive=5000, progressive_threshold=10000)
)

Memory Management

# Optimize memory usage for batch rendering
charts = []
for data_chunk in large_dataset_chunks:
    chart = create_chart(data_chunk)
    charts.append(chart.render_embed())
    del chart  # Free memory

# Combine rendered charts
final_html = combine_charts(charts)

Output Formats

Supported output formats and their characteristics.

HTML Output

  • Interactive: Full interactivity with tooltips, zoom, pan
  • Responsive: Adapts to container size
  • JavaScript Required: Requires JavaScript execution
  • File Size: Larger due to JavaScript libraries

Image Output

  • Static: No interactivity
  • Portable: Works without JavaScript
  • Print-Ready: Suitable for reports and publications
  • File Size: Smaller, faster loading

SVG Output

  • Vector: Scalable without quality loss
  • Editable: Can be modified in vector graphics software
  • Text-Searchable: Text remains selectable
  • Browser Support: Excellent modern browser support

PDF Output

  • Print-Ready: Optimized for printing
  • Professional: Suitable for business reports
  • Archival: Long-term document preservation
  • Driver-Dependent: Requires compatible browser driver

Error Handling

Common rendering issues and solutions.

# Handle rendering errors gracefully
try:
    chart.render("output.html")
except Exception as e:
    print(f"Rendering error: {e}")
    # Fallback to embedded rendering
    html_content = chart.render_embed()
    with open("output.html", "w", encoding="utf-8") as f:
        f.write(f"<html><body>{html_content}</body></html>")

# Validate chart before rendering
def validate_chart(chart):
    """Check if chart has required data and options."""
    if not chart.options.get("series"):
        raise ValueError("Chart has no data series")
    return True

# Memory-safe batch rendering
def render_charts_safely(charts, output_dir):
    """Render multiple charts with memory management."""
    for i, chart in enumerate(charts):
        try:
            chart.render(f"{output_dir}/chart_{i}.html")
        except Exception as e:
            print(f"Failed to render chart {i}: {e}")
        finally:
            del chart  # Free memory

Install with Tessl CLI

npx tessl i tessl/pypi-pyecharts

docs

3d-charts.md

basic-charts.md

composite-charts.md

geographic-charts.md

index.md

options.md

rendering.md

utilities.md

tile.json