Home > Backend Development > Golang > How to build chart components using Go language and Vue.js

How to build chart components using Go language and Vue.js

PHPz
Release: 2023-06-17 12:46:48
Original
1635 people have browsed it

With the advent of the Internet era, data analysis and visual display have become a necessary part of various applications. With the development of modern web applications, how to use easy-to-use and efficient tools to process data and create beautiful chart components has become an important topic. In this article, we will introduce how to build chart components using Go language and Vue.js.

Go language and Vue.js are two popular open source tools, both of which have received widespread attention and use. Go language is an emerging programming language designed to provide efficiency, reliability and simplicity, and has become a popular server-side programming language. Vue.js is a popular JavaScript framework especially useful for building interactive user interface components like charts. Both the Go language and Vue.js are easy to learn and use, and easy to extend.

In this article, we will use Go language to write back-end code, process data and provide chart data API. We will then use the Vue.js front-end framework to create chart components and get data from the back-end, then visualize the data. We will use two popular charting libraries: Chart.js and Plotly.js. These libraries use HTML5 Canvas and D3.js technology to create responsive charts.

First, let's start by creating a data processing API. In our example, we will use Go language to write the backend code. To simplify the process, we will use the Echo framework to create our API routes and controllers. In the data.go file, we will define a struct called data that contains the five fields that we will pass from the frontend to the API:

type data struct {
        Month    int     `json:"month"`
        Year     int     `json:"year"`
        Revenue  int     `json:"revenue"`
        Expenses int     `json:"expenses"`
        Profit   int     `json:"profit"`
}
Copy after login

The next step is in our main.go file Create API routes and controllers. We will define a route processing function named getDataHandler, which will accept the GET request sent by the Vue.js component, parse the data, perform data processing and return the data. The following is the specific code:

func getDataHandler(c echo.Context) error {
    // 解析数据
    year, _ := strconv.Atoi(c.QueryParam("year"))
    month, _ := strconv.Atoi(c.QueryParam("month"))

    // 处理数据,此处我们省略了数据查询和处理代码

    // 返回数据
    response := []data{
        {Month: 1, Year: 2022, Revenue: 100000, Expenses: 50000, Profit: 50000},
        {Month: 2, Year: 2022, Revenue: 75000, Expenses: 40000, Profit: 35000},
        {Month: 3, Year: 2022, Revenue: 120000, Expenses: 80000, Profit: 40000},
        {Month: 4, Year: 2022, Revenue: 85000, Expenses: 60000, Profit: 25000},
        {Month: 5, Year: 2022, Revenue: 105000, Expenses: 75000, Profit: 30000},
        {Month: 6, Year: 2022, Revenue: 95000, Expenses: 55000, Profit: 40000},
        {Month: 7, Year: 2022, Revenue: 140000, Expenses: 65000, Profit: 75000},
        {Month: 8, Year: 2022, Revenue: 120000, Expenses: 45000, Profit: 75000},
        {Month: 9, Year: 2022, Revenue: 115000, Expenses: 50000, Profit: 65000},
        {Month: 10, Year: 2022, Revenue: 95000, Expenses: 60000, Profit: 35000},
        {Month: 11, Year: 2022, Revenue: 80000, Expenses: 40000, Profit: 40000},
        {Month: 12, Year: 2022, Revenue: 125000, Expenses: 80000, Profit: 45000},
    }
    return c.JSON(http.StatusOK, response)
}
Copy after login

Now we have created an API that can accept GET requests sent by Vue.js components and return data. The next step is to create a Vue.js component that will get the data from the API and create the chart. We'll use Chart.js and Plotly.js to demonstrate how to build two different types of charts.

First, we will create a bar chart component to display monthly sales revenue and expenses. We define a component named "BarChart" in Vue.js. In Vue.js, we will use the axios library to handle HTTP requests and get data from an API written in Go language. In the mounted hook function, we will use the axios library to get the data from the API and the Chart.js library to create the bar chart. Here is our component code:

<template>
    <div>
        <canvas ref="bar"></canvas>
    </div>
</template>

<script>
    import axios from 'axios';
    import Chart from 'chart.js';

    export default {
        name: 'BarChart',
        mounted() {
            axios.get('/api/data?year=2022').then(response => {
                let data = response.data;

                let ctx = this.$refs.bar.getContext('2d');
                let myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: data.map(d => d.Month),
                        datasets: [{
                            label: 'Revenue',
                            data: data.map(d => d.Revenue),
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1
                        }, {
                            label: 'Expenses',
                            data: data.map(d => d.Expenses),
                            backgroundColor: 'rgba(255, 99, 132, 0.2)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                });
            });
        }
    }
</script>
Copy after login

In this component, we get the data from the API and then use the Chart.js library to create the bar chart. Please note that we use Vue.js's $refs attribute to define a reference to the canvas element in the template, and then use it in the mounted hook function to obtain the context of the canvas. We specify the type of bar chart and create two data collections for income and expenses, then use the beginAtZero property to scale the y-axis.

Next, we will create a scatter chart component to display sales revenue, expenses, and profit. Again, we get the data from the API and plot a scatter plot by month. We will use Plotly.js and Vue.js components to draw the scatter plot. The following is our component code:

<template>
    <div :id="divId"></div>
</template>

<script>
    import axios from 'axios';
    import Plotly from 'plotly.js-basic-dist';

    export default {
        props: ['chartData'],
        data() {
            return {
                divId: `scatter${Math.floor(Math.random() * 1000000)}`,
                layout: {
                    title: 'Revenue, Expenses and profit by Month',
                    xaxis: {
                        title: 'Revenue'
                    },
                    yaxis: {
                        title: 'Expenses'
                    },
                    hovermode: 'closest'
                }
            }
        },
        mounted() {
            axios.get('/api/data?year=2022').then(response => {
                let data = response.data;

                let scatterData = {
                    x: data.map(d => d.Revenue),
                    y: data.map(d => d.Expenses),
                    mode: 'markers',
                    hovertemplate: `Revenue: %{x:$,.2f}<br>Expenses: %{y:$,.2f}<br>Profit: %{text:$,.2f}`,
                    text: data.map(d => d.Profit),
                    marker: {
                        color: data.map(d => d.Profit),
                        size: 20,
                        line: {
                            width: 0.5,
                            color: 'white'
                        }
                    }
                };

                Plotly.newPlot(this.divId, [scatterData], this.layout);
            });
        }
    }
</script>

<style scoped>
    .plot {
        max-width: 100%;
        height: 500px;
    }
</style>
Copy after login

In this Vue.js component file, we will use the Vue.js props attribute to pass data to our component. Again, we use axios library to get data from API. For each month, we create a point and specify income on the horizontal axis and expenses on the vertical axis. We also tell Plotly.js to use Profit as text to display on each point, and set the size and color for each point.

By using Vue.js and Go language, we have created two chart components. Using these components we can obtain data and display sales data interactively. Furthermore, using Chart.js and Plotly.js, we can create beautiful charts and highly customize them. These methods can be applied to other data visualization projects and make building data visualization websites and applications fast, easy, and scalable.

The above is the detailed content of How to build chart components using Go language and Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template