Home Backend Development Golang Learn to use ECharts and golang to create stunning statistical charts

Learn to use ECharts and golang to create stunning statistical charts

Dec 17, 2023 am 10:26 AM
golang echarts statistic chart

Learn to use ECharts and golang to create stunning statistical charts

Learn to use ECharts and Golang to create stunning statistical charts

With the continuous growth of data and the development of technology, data visualization has become an important part of conveying information and displaying results. important way. The design and presentation of data statistical charts not only require beautiful and intuitive display effects, but also require a high degree of interactivity and flexibility. This article will introduce how to use ECharts and Golang, two powerful tools, to achieve stunning statistical charts.

ECharts is a JavaScript-based data visualization library open sourced by Baidu. It has rich data visualization types and supports multiple platforms and browsers. Through ECharts, we can easily draw various forms of charts, such as line charts, bar charts, pie charts, etc. At the same time, ECharts also has powerful interactive capabilities, which can realize interaction between users and charts through mouse interaction, chart component linkage, etc.

Golang is a programming language developed by Google, which is efficient, simple and safe. Through Golang, we can quickly build high-performance web applications and combine them with ECharts to achieve a complete process of data acquisition, processing and display.

Next, we will use a practical case to demonstrate how to use ECharts and Golang to build a stunning statistical chart.

First, let us consider a requirement: Suppose we want to count the monthly sales of a certain region and display it in the form of a line chart. We can obtain monthly sales data through Golang and draw the corresponding line chart through ECharts.

First of all, in Golang, we need to use an HTTP request to obtain sales data. You can use the famous HTTP request library "gorilla/mux".

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

type Sale struct {
    Month  string  `json:"month"`
    Amount float64 `json:"amount"`
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/sales", getSales).Methods("GET")
    log.Fatal(http.ListenAndServe(":8000", r))
}

func getSales(w http.ResponseWriter, r *http.Request) {
    sales := []Sale{
        {Month: "Jan", Amount: 1000.00},
        {Month: "Feb", Amount: 1500.00},
        {Month: "Mar", Amount: 2000.00},
        // 其他月份的销售额数据
    }

    json.NewEncoder(w).Encode(sales)
}
Copy after login

The above code uses the gorilla/mux library to create a route and defines a GET request processing function getSales, which returns a JSON array containing sales data. In the getSales function, we define a fixed example to simulate sales data, which you can modify according to the actual situation.

Next, we use ECharts to draw the line chart, which can be achieved by introducing the ECharts library file in the HTML file and calling the corresponding API in the JavaScript code.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>销售统计</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.1.2/dist/echarts.min.js"></script>
</head>

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

    <script>
        var chart = echarts.init(document.getElementById('chart'));

        // 发起HTTP请求获取销售额数据
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://localhost:8000/sales", true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var sales = JSON.parse(xhr.responseText);
                var months = [];
                var amounts = [];
                for (var i = 0; i < sales.length; i++) {
                    months.push(sales[i].month);
                    amounts.push(sales[i].amount);
                }

                // 绘制折线图
                chart.setOption({
                    xAxis: {
                        data: months
                    },
                    yAxis: {},
                    series: [{
                        name: '销售额',
                        type: 'line',
                        data: amounts
                    }]
                });
            }
        }
        xhr.send();
    </script>
</body>

</html>
Copy after login

In the above code, we initiate an HTTP request through XMLHttpRequest to obtain sales data, and then parse and use the ECharts API to draw a line chart. When drawing a line chart, we use month as the x-axis and sales as the y-axis. We configure the style and data of the chart by setting parameters such as xAxis, yAxis, and series.

Through the above code examples, we can see that stunning statistical charts can be easily achieved using ECharts and Golang. You only need to obtain the data through HTTP requests, and then use ECharts to draw charts on the front end, which can be easily displayed. At the same time, the powerful interactive capabilities of ECharts can further enhance the visualization effect of charts, allowing users to have more in-depth interactions with charts.

Of course, the above example is just a simple demonstration. In practice, you need to adjust and expand it according to specific needs and data structures. I hope this article helps you understand how to use ECharts and Golang to create stunning statistical charts!

The above is the detailed content of Learn to use ECharts and golang to create stunning statistical charts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

See all articles