Skip to content

Chart Examples (Chart.js)

This page demonstrates Chart.js usage within Phantom Documentation Kit. By reviewing this page, you can examine chart implementations and their live code examples.

Required Configuration

To use Chart.js in your markdown files, you must include the following YAML front matter at the top of your document:

---
extra_javascript:
  - assets/javascripts/chart.js
---
Without this configuration, charts will not render properly.

Line Chart

A simple responsive line chart showing monthly data trends.

Bar Chart

A responsive bar chart displaying category comparisons.

Multiple Axis (Line and Bar) Chart

A combination chart with multiple y-axes showing different metrics.

Pie Chart

A responsive pie chart showing distribution of data.

Donut Chart

A responsive donut chart with center text displaying total value.

Chart.js Implementation

The Chart.js implementation within Phantom Documentation Kit is provided through the overrides/assets/javascripts/chart.js file. This implementation offers the following features:

How It Works

  1. Automatic Initialization: On page load, all .chart-container elements are automatically scanned and charts are created.

  2. JSON-Based Configuration: Charts are configured via the data-chart-config attribute in JSON format. This approach:

    • Enables chart creation without writing JavaScript code
    • Provides clean and readable structure within Markdown files
    • Offers a secure configuration method
  3. Theme Support: The implementation automatically detects Material for MkDocs theme changes:

    • Charts automatically update during light/dark theme transitions
    • Text colors, grid lines, and backgrounds become theme-compatible
    • Theme changes are monitored using the MutationObserver API
  4. Responsive Design: Default settings for all charts:

    • responsive: true - Automatic scaling based on container size
    • maintainAspectRatio: false - Flexible aspect ratio
    • aspectRatio: 2 - Default 2:1 aspect ratio

Technologies Used

  • Chart.js v4.4.7: Optimized version through vendor builder
  • Lazy Loading: Chart.js is loaded only on pages containing charts
  • Theme Observer: Real-time theme change monitoring
  • JSON Parse: Secure configuration reading

Chart Creation Process

1. HTML element scanning → .chart-container
2. JSON config reading → data-chart-config attribute
3. Apply theme colors → applyThemeToConfig()
4. Canvas creation → Chart.js render
5. Theme change listener → updateCharts()

Chart.js documentation related to our implementation: