Introduce JS
You can get Apache EChartsTM in the following ways.
-
From Download Interface of Apache ECharts official website Get the official source code package and build it.
-
At ECharts GitHub Get.
-
For details, see install nphart, save npecm“ Using ecarts in webpack"
-
Pass jsDelivr Wait for CDN introduction
Directly import the constructed echarts file by labeling
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- introduce ECharts file --> <script src="echarts.min.js"></script> </head> </html>
Draw a chart
Before drawing, we need to prepare a DOM container with height and width for ECharts.
<body> <!-- by ECharts Prepare one with size (width and height) DOM --> <div id="main" style="width: 600px;height:400px;"></div> </body>
Then you can pass echarts.init Method to initialize an echarts instance and setOption Method to generate a simple histogram. Here is the complete code.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ECharts</title> <!-- introduce echarts.js --> <script src="echarts.min.js"></script> </head> <body> <!-- by ECharts Prepare one with size (width and height) Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // Initialize the ecarts instance based on the prepared dom var myChart = echarts.init(document.getElementById('main')); // Specify configuration items and data for the chart var option = { title: { text: 'ECharts Getting started example' }, tooltip: {}, legend: { data:['sales volume'] }, xAxis: { data: ["shirt","cardigan","Chiffon shirt","trousers","high-heeled shoes","Socks"] }, yAxis: {}, series: [{ name: 'sales volume', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; // Use the configuration item and data you just specified to display the chart. myChart.setOption(option); </script> </body> </html>
So your first chart is born!
promote
You can create more than one instance of} eckarts in a web page. Multiple charts, coordinate systems, and so on can be created in each instance of "echarts" (described by "option"). By preparing a DOM node (as the rendering container of ecarts), you can create an instance of ecarts on it. Each ecarts instance has a single DOM node.
series
Series( series )Is a very common noun. In echarts, series( series )It refers to a set of values and the graph they map to. The word "series" may originally come from "a series of data", but its extended concept in echarts represents not only data, but also a graph mapped by data. Therefore, a {series contains at least a set of values, chart type (series.type), and other parameters about how these data are mapped into a graph.
In ecarts, series.type is the type of chart. series.type at least: line (line chart) bar (histogram) pie (pie chart) scatter (scatter chart) graph (diagram) tree (tree chart)
As shown in the figure below, three , series are declared in , option , on the right( series): pie (pie chart series) line (line chart series) bar (histogram Series), each series has the data he needs( series.data).
component
On top of the series, various contents in echarts are abstracted as "components". For example, there are at least these components in ecarts: xAxis (X axis of rectangular coordinate system) yAxis (Y axis of rectangular coordinate system) grid (rectangular coordinate system base plate) angleAxis (polar coordinate system angle axis) radiusAxis (polar coordinate system radius axis) polar (polar coordinate system base plate) geo (geographic coordinate system) dataZoom (data area scaling component) visualMap (visual mapping component) tooltip (prompt box component) toolbox (toolbar component) series (Series)
We noticed that in fact, the series( series )It is also a kind of component, which can be understood as: series is a component dedicated to drawing "diagram".
As shown in the figure below, each component (including Series) is declared in the , option , on the right, and each component appears in the figure.
Describe the chart with option
The concept of "option" has appeared above. Users of echarts use the option to describe their various needs for charts, including what data they have, what charts they want to draw, what the charts look like, what components they contain, what things the components can operate, and so on. In short, option describes: data, how data is mapped into graphics, and interactive behavior.
// Create an echorts instance. var dom = document.getElementById('dom-id'); var chart = echarts.init(dom); // Use option to describe 'data', 'how to map data into graphics',' interactive behavior ', etc. // option is a large JavaScript object. var option = { // Each attribute of option is a kind of component. legend: {...}, grid: {...}, tooltip: {...}, toolbox: {...}, dataZoom: {...}, visualMap: {...}, // If there are multiple similar components, it is an array. For example, here are three X axes. xAxis: [ // Each item of the array represents a component instance, and the "subtype" is described by type. {type: 'category', ...}, {type: 'category', ...}, {type: 'value', ...} ], yAxis: [{...}, {...}], // There are multiple series here, which also form an array. series: [ // For each series, there is also a type to describe "subtype", i.e. "chart type". {type: 'line', data: [['AA', 332], ['CC', 124], ['FF', 412], ... ]}, {type: 'line', data: [2231, 1234, 552, ... ]}, {type: 'line', data: [[4, 51], [8, 12], ... ]} }] }; // Call setOption, enter the option into ecarts, and then ecarts renders the chart. chart.setOption(option);
In the series series.data This is the data of this series. Another way of description is that the series of data from dataset Middle take:
var option = { dataset: { source: [ [121, 'XX', 442, 43.11], [663, 'ZZ', 311, 91.14], [913, 'ZZ', 312, 92.12], ... ] }, xAxis: {}, yAxis: {}, series: [ // The data is taken from the dataset, and the value in encode is dataset index dimension of source (i.e. the column) {type: 'bar', encode: {x: 1, y: 0}}, {type: 'bar', encode: {x: 1, y: 2}}, {type: 'scatter', encode: {x: 1, y: 3}}, ... ] };
Personalized configuration
Shadow configuration
There are some general styles in ECharts, such as shadow, transparency, color, border color, border width, etc. these styles are generally listed in the series itemStyle Set in. For example, the style of shadows can be set through the following configuration items:
itemStyle: { // Shadow size shadowBlur: 200, // Offset in shadow horizontal direction shadowOffsetX: 0, // Offset in vertical direction of shadow shadowOffsetY: 0, // Shadow color shadowColor: 'rgba(0, 0, 0, 0.5)' }
The emphasis of itemStyle is the highlight style when hovering the mouse. In this example, the shadow is added under the normal style, but it is more likely to be highlighted by the shadow when hovering.
itemStyle: { emphasis: { shadowBlur: 200, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
Dark background and light label
Now we need to change the whole theme to the dark theme as in the initial example, which requires changing the background color and text color.
The background color is global, so it is set directly under option backgroundColor
setOption({ backgroundColor: '#2c343c' })
The style of text can be set globally textStyle.
setOption({ textStyle: { color: 'rgba(255, 255, 255, 0.3)' } })
You can also set each series separately, and the text of each series is set in label.textStyle.
label: { textStyle: { color: 'rgba(255, 255, 255, 0.3)' } }
For pie chart, set the color of the visual guide line of the label to light color.
labelLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.3)' } }
Asynchronous data loading
After initialization, it is directly filled in setOption , but in many cases, the data may need to be loaded asynchronously before filling. It is very simple to update asynchronous data in Apache EChartsTM , as long as the data and configuration items are filled in through , setOption , after asynchronously obtaining data through tools such as jQuery at any time after chart initialization.
var myChart = echarts.init(document.getElementById('main')); $.get('data.json').done(function (data) { myChart.setOption({ title: { text: 'Asynchronous data loading example' }, tooltip: {}, legend: { data:['sales volume'] }, xAxis: { data: ["shirt","cardigan","Chiffon shirt","trousers","high-heeled shoes","Socks"] }, yAxis: {}, series: [{ name: 'sales volume', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }); });
Or set other styles first, display an empty rectangular coordinate axis, and then fill in the data after obtaining the data.
var myChart = echarts.init(document.getElementById('main')); // Displays the title, legend, and empty axis myChart.setOption({ title: { text: 'Asynchronous data loading example' }, tooltip: {}, legend: { data:['sales volume'] }, xAxis: { data: [] }, yAxis: {}, series: [{ name: 'sales volume', type: 'bar', data: [] }] }); // Load data asynchronously $.get('data.json').done(function (data) { // Fill in data myChart.setOption({ xAxis: { data: data.categories }, series: [{ // Corresponding to the corresponding series according to the name name: 'sales volume', data: data.data }] }); });
loading animation
If the data is loaded for a long time, putting an empty coordinate axis on the canvas will also make the user feel whether there is a bug. Therefore, a loading animation is needed to prompt the user that the data is being loaded.
ECharts provides a default animation loading. Just call showLoading Method display. Call after data loading is completed hideLoading Method hides the loaded animation.
myChart.showLoading(); $.get('data.json').done(function (data) { myChart.hideLoading(); myChart.setOption(...); });
Dynamic update of data
ECharts is driven by data, and the change of data drives the change of chart display. Therefore, the implementation of dynamic data becomes extremely simple.
All data updates are passed setOption To achieve, you only need to obtain data regularly, setOption Fill in the data without considering the changes in the data. ECharts will find the differences between the two groups of data, and then express the changes in the data through appropriate animation.
Add interactive components to the diagram
Legend components legend Title Component title Visual mapping component visualMap , data area scaling component dataZoom . timeline components timeline
Next, zoom the components in the data area dataZoom As an example, this paper introduces how to add this component.
Events and behaviors
In Apache EChartsTM's chart, the user's action will trigger the corresponding event. Developers can listen to these events and then handle them through callback functions, such as jumping to an address, popping up a dialog box, or drilling down data, etc.
In ECharts 3, the binding event is the same as 2 through on Method, but the event name is simpler than 2. In ECharts 3, the event name corresponds to the DOM event name, which is a lowercase string. The following is an example of binding click operation.
myChart.on('click', function (params) { // The name of the console print data console.log(params.name); });
In ECharts, events are divided into two types: one is triggered when the user clicks with the mouse or the graph of hover chart, and the other is triggered by the user after using the interactive components, such as when switching the legend switch 'legendselectchanged' Event (it should be noted here that switching the legend switch will not trigger the 'legendselected' event), which is triggered when the data area is scaled 'datazoom' Events, etc.
Handling of mouse events
ECharts supports normal mouse event types, including 'click', 'dblclick', 'mousedown', 'mousemove', 'mouseup', 'mouseover', 'mouseout', 'globalout' and 'contextmenu' events. Let's take a look at a simple example of clicking on the histogram to open the corresponding Baidu search page.
// Initialize the ECharts instance based on the prepared dom var myChart = echarts.init(document.getElementById('main')); // Specify configuration items and data for the chart var option = { xAxis: { data: ["shirt","cardigan","Chiffon shirt","trousers","high-heeled shoes","Socks"] }, yAxis: {}, series: [{ name: 'sales volume', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; // Use the configuration item and data you just specified to display the chart. myChart.setOption(option); // Handle the click event and jump to the corresponding Baidu search page myChart.on('click', function (params) { window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name)); });
All mouse events contain the parameter params, which is an object containing the data information of the click graph. The format is as follows:
{ // The name of the component to which the currently clicked graphic element belongs, // Its values include 'series',' markLine ',' markPoint ',' timeLine ', etc. componentType: string, // Series type. Values may be: 'line', 'bar', 'pie', etc. Meaningful when componentType is' series'. seriesType: string, // Series in the passed in option index in series. Meaningful when componentType is' series'. seriesIndex: number, // Series name. Meaningful when componentType is' series'. seriesName: string, // Data name name: string, // index of data in the incoming data array dataIndex: number, // Incoming raw data item data: Object, // sankey, graph and other charts contain both nodeData and edgeData data, // The value of dataType will be 'node' or 'edge', indicating whether the current click is on node or edge. // In most other charts, there is only one kind of data, and dataType is meaningless. dataType: string, // Incoming data value value: number|Array // The color of the data graph. Meaningful when componentType is' series'. color: string }
How to distinguish where the mouse clicks:
myChart.on('click', function (params) { if (params.componentType === 'markPoint') { // Click on the markPoint if (params.seriesIndex === 5) { // Click on the markPoint of the series with index 5. } } else if (params.componentType === 'series') { if (params.seriesType === 'graph') { if (params.dataType === 'edge') { // Click on the edge of the graph. } else { // Click on the node of the graph. } } } });
Use query to trigger callback only for graphic elements of specified components:
chart.on(eventName, query, handler);
query , can be , string , or , Object.
If , string , indicates the component type. The format can be 'mainType' or 'mainType subType'. For example:
chart.on('click', 'series', function () {...}); chart.on('click', 'series.line', function () {...}); chart.on('click', 'dataZoom', function () {...}); chart.on('click', 'xAxis.category', function () {...});
If it is an Object, it can contain one or more of the following attributes, and each attribute is optional:
{ <mainType>Index: number // Component index <mainType>Name: string // Component name <mainType>Id: string // Component id dataIndex: number // Data item index name: string // Data item name dataType: string // Data item type, such as' node 'and' edge 'in the diagram element: string // name of el in custom series }