Master ECharts: From Your First Chart to Advanced Data Visualizations
This comprehensive guide walks you through the fundamentals of Apache ECharts, showing how to set up the library, understand core concepts like option, series, axes, and datasets, and apply them in real‑world scenarios such as class performance analysis, subject distribution, correlation studies, and top‑student radar charts, while also covering interactivity, responsiveness, visual mapping, and animation techniques.
❝ This article serves as your ECharts beginner's guide, systematically outlining the core knowledge of ECharts and, through a practical "High‑School Final Exam Score Analysis" case, teaching you step‑by‑step how to turn data into insightful charts. ❞
Frontend development is essentially about visualizing data. Presenting raw numbers in an intuitive, easy‑to‑understand way is a key challenge, and charts are one of the best solutions.
From simple health‑app weekly sleep bar charts to complex real‑time stock dashboards, charts convey information far more efficiently than plain text or tables, helping users quickly spot patterns, trends, and outliers.
Among many options, Apache ECharts stands out for its rich chart types, powerful interactions, flexible configuration, and active community, making it a top choice for front‑end developers worldwide.
Like the GSAP animation library, many first encounter ECharts with the impression of "numerous configuration options" and a "steep learning curve"—but is that really the case?
When we take a closer look, the core concepts are straightforward. All chart configurations revolve around a few fixed modules: container & size, style, dataset, axes, visual mapping, legend , etc.
The official ECharts site offers countless examples covering virtually every chart effect, and its configuration documentation is itself interactive—modify the config and see the result instantly, dramatically lowering the learning barrier.
ECharts First Experience: Drawing Your First Chart
The best way to learn any technology is to start with a "Hello World".
Import Method
We will use the simplest method: include the library via CDN. Just add a <script> tag to your HTML file. This requires no build tools and is perfect for quick prototyping.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>Complete Example
Copy the following code into an HTML file and open it in a browser to see your first ECharts chart.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts Intro Example</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 1. Initialize the chart instance based on the prepared DOM
var myChart = echarts.init(document.getElementById('main'));
// 2. Specify chart configuration and data
var option = {
title: { text: 'My First ECharts Chart' },
tooltip: {},
xAxis: { data: ['Shirt','Woolen','Silk','Pants','Heels','Socks'] },
yAxis: {},
series: [{ name: 'Sales', type: 'bar', data: [5,20,36,10,10,20] }]
};
// 3. Use the configuration to render the chart
myChart.setOption(option);
</script>
</body>
</html>This simple example reveals the core workflow of ECharts: Import script → Prepare container → Initialize instance → Set option . All chart implementations are encapsulated in the large option object.
Core Concept Breakdown: The option Object
The option object is a massive JavaScript object that describes everything about a chart: data, style, interaction, animation, and more. Understanding its structure is equivalent to mastering ECharts.
Let's peel it layer by layer.
series : Series and Chart Types
seriesis the most important configuration item in ECharts. It is an array where each object represents a "series"—a set of related data and the rules for visualizing it.
What is a "series"? Think of it as a group of data together with the way it should be visualized. Multiple series can coexist in one chart, each with its own type (e.g., bar, line).
series: [
{ name: 'Sales', type: 'bar', data: [5,20,36,10,10,20] }
]Adding another series (e.g., a line for "Production") is as simple as appending another object to the array.
series: [
{ name: 'Sales', type: 'bar', data: [...] },
{ name: 'Production', type: 'line', data: [...] }
]ECharts supports many chart types, such as line, bar, pie, scatter, radar, map, tree, graph, etc.
xAxis & yAxis : Axes
For most charts (line, bar, scatter), axes are essential. ECharts configures them via xAxis and yAxis, which together define a Cartesian coordinate system (grid) .
Key parts of an axis include axis line, ticks, tick labels, and axis name .
Typical xAxis configuration:
xAxis: {
type: 'category',
data: ['Jan','Feb','Mar','Apr','May'],
name: 'Month',
axisLine: { show: true },
axisTick: { show: true },
axisLabel: { color: '#333', fontSize: 12 }
}The type property determines how data is interpreted: 'value': numeric axis, suitable for continuous data. 'category': categorical axis, suitable for discrete categories. 'time': time axis, automatically formats timestamps. 'log': logarithmic axis, useful for data with large ranges. yAxis is configured similarly and can have multiple axes linked to series via xAxisIndex and yAxisIndex.
grid : Plotting Grid
The grid component defines the position and size of the Cartesian coordinate system inside the container. Adjust left, right, top, bottom to control margins, and set containLabel: true to automatically accommodate axis labels.
grid: {
left: '3%',
right: '4%',
bottom: '3%',
top: '10%',
containLabel: true
}title : Chart Title
A clear title helps users understand the chart purpose. Both main title and subtitle can be configured.
title: {
text: 'Monthly Website Visits',
subtext: 'Data source: simulated',
left: 'center',
textStyle: { color: '#c23531', fontSize: 20 }
}tooltip : Tooltip
When the mouse hovers over a data item, tooltip displays detailed information, an essential part of chart interactivity.
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' }
}The trigger can be 'item' (single data item) or 'axis' (all series at a specific axis value).
legend : Legend
When a chart contains multiple series, the legend component helps differentiate them. Clicking a legend item toggles the visibility of the corresponding series.
legend: {
data: ['Sales','Production'],
top: 'bottom'
}dataset : Data Set
Since ECharts 4, the dataset component enables a clear separation of data and configuration. It allows data reuse, transformation, and cleaner code.
var option = {
dataset: {
source: [
['product','2015','2016','2017'],
['Matcha Latte',43.3,85.8,93.7],
['Milk Tea',83.1,73.4,55.1],
['Cheese Cocoa',86.4,65.2,82.5],
['Walnut Brownie',72.4,53.9,39.1]
]
},
xAxis: { type: 'category' },
yAxis: {},
series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
};With dataset, you can map columns to axes and series via encode, avoiding repetitive series.data definitions.
Practical Project: High‑School Final Exam Multi‑Dimensional Analysis
To make the theory concrete, we apply the concepts to a comprehensive case that analyzes a high‑school grade's exam results from multiple dimensions.
Scenario 1: Average Total Score per Class (Bar Chart)
Goal: Visually compare average total scores of each class.
var barChart = echarts.init(document.getElementById('bar-chart'));
var barChartOption = {
title: { text: 'Average Total Score per Class', left: 'center' },
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: { type: 'category', data: classNames, axisLabel: { interval: 0, rotate: 30 } },
yAxis: { type: 'value', name: 'Average Score' },
series: [{ name: 'Average Score', type: 'bar', barWidth: '60%', data: avgScores }]
};
barChart.setOption(barChartOption);Scenario 2: Single‑Subject Score Distribution (Pie / Rose Chart)
Goal: Show the distribution of math scores for Class 1.
var pieChart = echarts.init(document.getElementById('pie-chart'));
var pieChartOption = {
title: { text: 'Class 1 Math Score Distribution', subtext: 'Final Exam', left: 'center' },
tooltip: { trigger: 'item', formatter: '{a}<br/>{b} : {c} students ({d}%)' },
legend: { orient: 'vertical', left: 'left', data: distribution.map(i => i.name) },
series: [{ name: 'Score Distribution', type: 'pie', radius: '50%', center: ['50%','60%'], data: distribution }]
};
pieChart.setOption(pieChartOption);Setting roseType: 'area' turns it into a Rose (Nightingale) chart for stronger visual impact.
Scenario 3: Physics‑Chemistry Score Correlation (Scatter Chart)
Goal: Determine whether students who excel in physics also perform well in chemistry.
var scatterChart = echarts.init(document.getElementById('scatter-chart'));
var scatterChartOption = {
title: { text: 'Physics‑Chemistry Correlation', left: 'center' },
grid: { left: '3%', right: '7%', bottom: '3%', containLabel: true },
xAxis: { type: 'value', name: 'Physics Score', splitLine: { lineStyle: { type: 'dashed' } } },
yAxis: { type: 'value', name: 'Chemistry Score', splitLine: { lineStyle: { type: 'dashed' } } },
tooltip: { trigger: 'item', formatter: function(p){ return p.data[3] + ' - ' + p.data[2] + '<br/>Physics: ' + p.data[0] + '<br/>Chemistry: ' + p.data[1]; } },
series: [{ name: 'Student', type: 'scatter', symbolSize: 6, data: correlationData, itemStyle: { color: 'rgba(25,100,150,0.6)' } }]
};
scatterChart.setOption(scatterChartOption);Observing the scatter distribution helps judge positive correlation and spot outliers.
Scenario 4: Top‑Student Subject Ability Model (Radar Chart)
Goal: Compare the top three students across all subjects.
var radarChart = echarts.init(document.getElementById('radar-chart'));
var radarChartOption = {
title: { text: 'Top Students Ability Radar', left: 'center' },
tooltip: { trigger: 'item' },
legend: { data: radarData.seriesData.map(i => i.name), bottom: 5 },
radar: { indicator: radarData.indicator, center: ['50%','50%'], radius: '65%' },
series: [{ name: 'Subject Ability', type: 'radar', data: radarData.seriesData, areaStyle: { opacity: 0.2 } }]
};
radarChart.setOption(radarChartOption);The radar chart instantly reveals each student's strengths and weaknesses; larger area indicates higher overall performance.
Advanced Topics & Techniques
Events & Interaction
ECharts instances can listen to mouse events. Use myChart.on('click', ...) to capture clicks for drill‑down or linked charts.
myChart.on('click', function (params) {
console.log(params.seriesName, params.name, params.dataIndex);
alert('You clicked: ' + params.name);
});Responsive Layout
Make charts adapt to window size changes by listening to the resize event and calling myChart.resize().
window.addEventListener('resize', function () { myChart.resize(); });Using percentage‑based layouts for grid, legend, etc., ensures perfect responsiveness.
Visual Mapping
The visualMap component maps data values to visual attributes such as color, size, or opacity, adding a third dimension to a two‑dimensional chart.
Animation Configuration
ECharts provides smooth animations. Global animation settings can be defined at the root level, while individual series can have their own animation delays.
{
animation: true,
animationDuration: 1000,
animationEasing: 'cubicOut',
series: [{
animationDelay: function (idx) { return idx * 10; }
}]
}Conclusion
We started from installing ECharts and creating a "Hello World" chart, then systematically dissected core configuration items such as series, xAxis, yAxis, grid, tooltip, legend, and dataset. By weaving these concepts into a real‑world "High‑School Exam Analysis" project, we built bar, pie, scatter, and radar charts.
Understanding each configuration block as a "visual building block" empowers you to design any chart you imagine. The journey of data visualization is vast—ECharts also offers graphic components, custom series, 3D GL charts, and more for you to explore.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
