Apache ECharts in Astro
Wed Apr 09 2025Similar to Observable Plot in Astro, I wanted to explore integrating Apache ECharts with Astro. ECharts is a powerful and loved charting library that offers a wide range of visualization options with excellent customization capabilities.
The Charts
Here’s a basic bar chart example using default options:
And a customized line chart showing weekly temperature data:
The Component
First, create a reusable component ApacheEChart.astro
:
---
interface Props {
width?: string;
height?: string;
options?: Record<string, any>;
}
const { width = "100%", height = "400px", options = {} } = Astro.props;
// Generate a unique ID for this chart instance
const chartId = `echart-${Math.random().toString(36).substring(2, 11)}`;
// Default chart options if none provided
const defaultOptions = {
title: {
text: "ECharts Example"
},
tooltip: {},
xAxis: {
data: ["A", "B", "C", "D", "E"]
},
yAxis: {},
series: [
{
name: "Sales",
type: "bar",
data: [5, 20, 36, 10, 10]
}
]
};
// Merge provided options with defaults
const chartOptions = Object.keys(options).length > 0 ? options : defaultOptions;
const serializedOptions = JSON.stringify(chartOptions);
---
<div id={chartId} style={`width: ${width}; height: ${height};`}></div>
<script define:vars={{ chartOptions: serializedOptions, chartId }}>
// Load ECharts from CDN
document.addEventListener("DOMContentLoaded", async () => {
// Load ECharts core
const echarts = await import("https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.esm.min.js");
// Initialize chart
const chartContainer = document.getElementById(chartId);
const chart = echarts.init(chartContainer);
// Set chart options
const options = JSON.parse(chartOptions);
chart.setOption(options);
// Handle resize
window.addEventListener("resize", () => {
chart.resize();
});
});
</script>
Using the Component
Then you can use it in any .astro
, .html
, or .mdx
file like this:
import ApacheEChart from "../../components/ApacheEChart.astro";
<ApacheEChart />
<ApacheEChart
height="300px"
options={{
// Your custom chart options
}}
/>
Advanced Usage
ECharts supports many types of visualizations like scatter plots, pie charts, candlestick charts, and more. You can also add features like:
- Multiple series
- Interactive legends
- Data zooming
- Tooltips with rich content
- Animation effects
Check the ECharts documentation for more examples and configuration options.
Next Steps
In a future, I’d love to work on a post to explore:
- Loading data at build time with DuckDB and passing it to the charts
- Building interactive dashboards with multiple charts