Getting started with Echarts data visualization: from basics to practice

introduction

The Importance of Data Visualization

Data visualization plays a vital role in the modern information age. It is not only a way of chart display, but also a powerful communication tool and decision support method.

insert image description here

  • Explore new dimensions of information: In today's digital world, data has become an indispensable resource in various fields. However, if the complex data cannot be clearly presented and understood, it will be difficult to exert its true value. At this point, the importance of data visualization emerges. Data visualization is more than simple charts and graphs, it is the art of turning abstract data into intuitive, easy-to-understand information.
  • The Power of Information: The human visual system is one of the most powerful perceptual tools, and data visualization takes advantage of it. In our daily life, we often hear the saying that "pictures are worth a thousand words", which is the core idea of ​​data visualization. By converting data into visual elements such as charts, graphs, maps, etc., people can understand information faster and more accurately, even those complex and abstract data.
  • Decision-making intelligence: Data plays a vital role in decision-making. Whether it is business management, policy formulation or scientific research, decision-making needs to be based on reliable data support. However, pure data is often too abstract to be understood by ordinary people. In this case, data visualization becomes a bridge to "translate" the language of data. By visualizing data into intuitive charts, decision makers can more intuitively understand the trends, regularities and anomalies contained in the data, so as to make more informed decisions.
  • Popularize data culture: With the advent of the data age, data culture has become more and more important. Data culture is not just the exclusive domain of professional data analysts, it should run through all levels and industries. However, ordinary people often feel at a loss when faced with a large amount of data. The emergence of data visualization has made data more popular, enabling more people to obtain information from data and make rational decisions.

Echarts resources and development

To start using Echarts, you can visit the official website (https://echarts.apache.org/) to get the latest Echarts resources and documents. The official website provides detailed documents covering the installation, configuration, usage and sample codes of various chart types of Echarts. You can download the JavaScript library file of Echarts from the official website, and integrate and configure it according to the documentation.

As an open source library, Echarts also provides a wealth of expansion and customization options to meet the needs of different projects. Here are some ways to extend functionality:

  • Plug-in extension: Echarts allows developers to write custom plug-ins to extend its functionality. According to project requirements, you can develop specific plug-ins to achieve more complex data visualization effects.
  • Theme customization: Echarts supports custom themes, you can adjust the color, style and font of the chart to suit the overall design style of the project.
  • Data interaction: Echarts provides rich interactive functions, including data filtering, legend switching, data zooming, etc. You can implement these interactions through configuration options that allow users to explore the data more deeply.
  • Map extension: If you need to display geographic data on the map, Echarts also provides map extension function. You can use GeoJSON data to create various types of maps, and add interactive effects and information display.
  • Animation effect: By configuring animation options, you can add dynamic effects to the chart to make the data changes more vivid and eye-catching.

Echarts Introduction and Development Preparation

What is Echarts

Echarts is an open source JavaScript data visualization library developed by Baidu, designed to help developers create rich, interactive charts and data visualizations. It supports a variety of chart types, including line charts, histograms, pie charts, scatter plots, etc., as well as geographic information visualizations such as maps and heat maps. Echarts has strong customization and flexibility, enabling developers to create various types of charts according to their needs.

insert image description here

ECharts is a powerful visualization library that provides a variety of chart types, including but not limited to the following:

chart type effect
Line Chart It is used to show the trend of data changes over time, and multiple polylines can be displayed for comparison and analysis.
Histogram (Bar Chart) The size of the data is represented by the height of the rectangle, which is suitable for comparing data of different categories or time periods.
Pie Chart Display the data in a circle or sector as a percentage, which is used to indicate the proportion of each part to the whole.
Scatter Chart Used to show the relationship between two variables, where each point represents a data instance.
Radar Chart Display data in multiple dimensions in a polygonal manner, and represent the size of the value by the length of each angle.
Map (Map Chart) It is used to display the data distribution and statistical results of geographical regions, which can be colored or marked according to different regions.
Heatmap (Heatmap) The intensity of the data is represented by the depth of the color, which is suitable for displaying the distribution of a large amount of discrete data.
Dashboard (Gauge Chart) It is used to display the value of an indicator within a specific range, and display the current value in the form of a dashboard.

Features and advantages of Echarts

As a powerful data visualization tool, Echarts has various chart types, powerful customization capabilities, good cross-platform compatibility and rich interactive functions, providing users with the opportunity to create impressive data visualization effects.

  • Diversified chart types: Echarts provides a variety of chart types, covering common line charts, histograms, pie charts, etc., as well as special types such as maps, radar charts, and heat maps, to meet different data presentation needs.
  • Powerful customization ability: Echarts allows users to highly customize all aspects of the chart, including chart style, data display, interactive effects, etc. Developers can create unique data visualizations by adjusting the style and behavior of each element according to specific needs.
  • Good cross-platform compatibility: Echarts supports a variety of front-end frameworks and libraries, including React, Vue, Angular, etc., making it easy to integrate with existing projects. In addition, Echarts also provides a responsive design for mobile devices to ensure good performance on different platforms.
  • Rich interactive functions: Echarts supports a variety of interactive functions, such as data filtering, legend switching, tooltips, etc. These interactive functions can help users explore data more deeply and analyze information from different angles.
  • Data-driven way of thinking: Echarts encourages the use of data-driven thinking for visual design. Users can simply configure data instead of manually drawing charts. This approach makes it easier to update and maintain charts.
  • Support for large data volumes: Echarts has the ability to handle large data volumes, and can optimize performance through data segmentation, asynchronous loading and other technologies to ensure smooth interaction and display effects under large-scale data.
  • Active community and document support: Echarts has an active community where users can obtain technical support, exchange experiences, and share their works. In addition, Echarts provides detailed official documents and examples to help users get started and solve problems more quickly.
  • Open source and free: Echarts is an open source project that can be used for free, whether it is a personal project or a commercial application, you can make full use of its functions without paying additional fees.

Install Echarts

Install using npm (Node Package Manager) (recommended): Open a command line terminal (such as Command Prompt for Windows or Terminal for macOS/Linux), and enter the following command:

npm install echarts

Introduce Echarts library

Use CDN (Content Distribution Network): If you don't want to install through npm, you can also directly introduce the CDN address of Echarts in the HTML file. <head>Add the following code to the tag in your HTML file :

<!-- Echarts 主文件 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>

Use local files: You can also download the source code files of Echarts to the local and reference them in the project. The source code can be found in Echarts' official GitHub repository (https://github.com/apache/echarts). <script>After downloading, reference the file in the HTML file via the tag.

Make sure that after installing or introducing Echarts, you can create various charts, set the data and style of the charts, etc. in the code. The official documentation provides detailed usage guidelines and examples to help users better start using Echarts.

first chart

Use Echarts to draw a simple histogram

Import ECharts library: import ECharts JavaScript files into your HTML files.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>

Create a DOM element containing the chart: Create a div element in the HTML file to hold the chart.

<div id="barChart" style="width: 600px; height: 400px;"></div>

Initialize the chart: In the JavaScript section, initialize an instance of ECharts and configure the basic parameters of the chart.

<script>
  // 初始化ECharts实例
  var myChart = echarts.init(document.getElementById('barChart'));

  // 配置图表的参数
  var option = {
    title: {
      text: '简单柱状图示例'
    },
    tooltip: {},
    xAxis: {
      data: ['项目A', '项目B', '项目C', '项目D', '项目E']
    },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: [150, 200, 300, 120, 250]
    }]
  };

  // 使用配置项显示图表
  myChart.setOption(option);
</script>

Data preparation and chart configuration

When using ECharts to create a chart, data preparation and chart configuration are required. Suppose we want to create a simple histogram showing the population of different cities. First, we need to prepare a data array containing city names and corresponding populations, for example:

var populationData = [
    { city: 'City A', population: 1500000 },
    { city: 'City B', population: 2200000 },
    { city: 'City C', population: 900000 },
    // ...更多城市数据
];

Chart configuration:
Next, we need to configure various parameters of the chart, including title, x-axis, y-axis, histogram data, etc. Here is a simple configuration example:

// 初始化 ECharts 实例
var myChart = echarts.init(document.getElementById('chart-container'));

// 配置项
var option = {
    title: {
        text: '城市人口数量统计'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    xAxis: {
        type: 'category',
        data: populationData.map(item => item.city) // 使用城市名称作为 x 轴数据
    },
    yAxis: {
        type: 'value',
        name: '人口数量'
    },
    series: [{
        type: 'bar',
        data: populationData.map(item => item.population) // 使用人口数量作为柱状图数据
    }]
};

// 将配置应用于图表实例
myChart.setOption(option);

In the above code, we create a simple histogram with the city name as the x-axis data and the population as the histogram data. Parameters such as title, prompt box, and coordinate axis can be set through configuration items.

Note that in the above example document.getElementById('chart-container')needs to be replaced with the actual HTML element ID you use.

Data Format Requirements

ECharts is a JavaScript chart library for visualizing data, which has certain requirements for data format. The following are several common ECharts data formats:

  1. Basic data format (two-dimensional array):
var data = [
  ['类别A', 100],
  ['类别B', 200],
  ['类别C', 300]
];
  1. Object array format:
var data = [
  { name: '类别A', value: 100 },
  { name: '类别B', value: 200 },
  { name: '类别C', value: 300 }
];
  1. Advanced data format (contains more properties):
var data = [
  { name: '类别A', value: 100, otherProperty: '其他属性值' },
  { name: '类别B', value: 200, otherProperty: '其他属性值' },
  { name: '类别C', value: 300, otherProperty: '其他属性值' }
];

During the development, select the appropriate data format according to the actual needs, and construct the data according to the requirements of the specific chart type in the ECharts document.

Chart title and label settings

Set various parameters of the chart, such as title, data, style, etc., as required.

var option = {
  title: {
    text: '柱状图示例'
  },
  xAxis: {
    data: ['类别A', '类别B', '类别C']
  },
  yAxis: {},
  series: [{
    name: '数量',
    type: 'bar',
    data: [100, 200, 300]
  }]
};

Adjust the style: You can adjust the style of the chart by modifying the configuration parameters. For example, colors, fonts, line styles, etc. can be modified.

option.title.textStyle = { color: 'red', fontSize: 18 };
option.series[0].itemStyle = { color: 'blue' };
chart.setOption(option);

Practice and performance optimization

insert image description here

Tips for Improving Chart Rendering Performance

To improve the rendering performance of ECharts charts, you can try the following techniques:

  1. Reduce the amount of data: If the graph displays a very large amount of data, consider aggregating or sampling the data to reduce the number of data points rendered. For example, data points can be reduced by averaging or sampling to reduce rendering complexity.
  2. Use asynchronous loading: When the chart data is large and the loading time is long, you can consider using asynchronous loading data to avoid page blocking. The initialization and rendering of the chart can be performed after the data loading is complete.
  3. Disable animation effects: In some cases, animation effects may affect the rendering performance of the chart, especially if the data volume is large or the update frequency is high. animationYou can disable the animation effect by setting it falseto improve rendering efficiency.
  4. Use a cache mechanism: If the data of the chart does not change frequently, you can consider caching the data to avoid repeated data processing and rendering operations. The chart data is only re-updated when the data changes.
  5. Avoid abusing chart interactions and events: Too many interactive functions and event listeners can cause chart performance to degrade. When designing charts, reasonably select the required interactive functions and avoid listening to too many events.
  6. Rational use of chart rendering modes: ECharts provides two rendering modes, namely canvasand svg. An appropriate rendering mode can be selected according to actual needs. Generally speaking, the canvas mode has advantages in large data volume and animation effects, while the svg mode is more suitable for static charts and fine rendering.

Responsive design and mobile adaptation

To realize the responsive design and mobile adaptation of ECharts, you can follow the steps below

  1. Set the container size: In the HTML file, set the appropriate width and height for the container element of the ECharts chart. Percentages or responsive units can be used to ensure that the container size adapts to the screen size.
<div id="chartContainer" style="width: 100%; height: 400px;"></div>
  1. Listen to window change events: Use JavaScript code to listen to window resize events so that the chart can be re-rendered when the window size changes.
window.addEventListener('resize', function () {
  chart.resize();
});
  1. Responsive configuration parameters: adjust the configuration parameters of ECharts charts according to different screen sizes or layout requirements. Configuration parameters can be dynamically modified through JavaScript code to achieve responsive effects.
window.addEventListener('resize', function () {
  var width = document.getElementById('chartContainer').clientWidth;
  var option = {
    // 根据容器宽度动态调整图表参数
    series: [{
      itemStyle: {
        color: (width < 600) ? 'red' : 'blue'
      }
    }]
  };
  chart.setOption(option);
});
  1. Mobile terminal adaptation: For mobile terminal devices, special adaptation processing may be required. The layout, font size, label display, etc. of the chart can be adjusted according to conditions such as screen width and device type.
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);

var option = {
  // 移动端适配
  grid: {
    top: '10%',
    left: (isMobile) ? '5%' : '8%',
    right: (isMobile) ? '5%' : '8%',
    bottom: '10%'
  },
  xAxis: {
    axisLabel: {
      fontSize: (isMobile) ? 10 : 12
    }
  }
};

Guess you like

Origin blog.csdn.net/weixin_42794881/article/details/132166119