Home Java javaTutorial Use ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison

Use ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison

Dec 17, 2023 pm 01:43 PM
java echarts multi-channel

Use ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison

Using ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison

With the continuous development of the Internet, more and more various types of graphs have emerged on the market. Products, and these products are often sold through different channels, such as online channels, offline channels, social media channels, etc. Therefore, statistics of sales data from different channels and comparison of sales performance between different channels are of great significance for corporate decision-making. This article will introduce how to use ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison.

1. Preparation

  1. Database table design

First, you need to design a database table to store sales data from different channels. This article takes the MySQL database as an example to create a database named "sales" and a data table named "channel_sales" in it, as shown below:

CREATE TABLE channel_sales (
id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Sales record ID',
channel_name varchar(50) NOT NULL COMMENT 'Channel name',
sales_date date NOT NULL COMMENT 'Sales date',
sales_amount decimal(10,2) NOT NULL COMMENT 'Sales amount',
PRIMARY KEY ( id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Sales data from different channels';

  1. Java background code writing

Next , Java back-end code needs to be written to provide the sales data in the database to the front-end page. This article uses the Spring Boot framework and uses MyBatis for data access. The code is as follows:

(1) Create ChannelSales entity class

public class ChannelSales {

private Integer id; // 销售记录ID
private String channelName; // 渠道名称
private Date salesDate; // 销售日期
private BigDecimal salesAmount; // 销售金额

// 省略getters和setters方法
Copy after login

}

(2) Create ChannelSalesMapper interface

@Mapper
public interface ChannelSalesMapper {

/**
 * 查询不同渠道的销售数据
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @return 销售数据列表
 */
List<ChannelSales> selectByDate(@Param("startDate") Date startDate,
                                @Param("endDate") Date endDate);
Copy after login

}

(3) Create ChannelSalesServiceImpl implementation class

@Service
public class ChannelSalesServiceImpl implements ChannelSalesService {

@Autowired
private ChannelSalesMapper channelSalesMapper;

/**
 * 查询不同渠道的销售数据
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @return 销售数据列表
 */
@Override
public List<ChannelSales> getSalesData(Date startDate, Date endDate) {
    return channelSalesMapper.selectByDate(startDate, endDate);
}
Copy after login

}

  1. Front-end page design

Finally, the front-end page needs to be designed to display the comparison of sales data from different channels. This article uses Echarts.js as the chart library and combines it with Bootstrap for page layout.

2. Implementation process

  1. Query sales data

First, obtain the query date range from the front-end page and send an Ajax request to the background to obtain Sales data from different channels. The code is as follows:

// Query date range picker
$('#date-range').daterangepicker({

startDate: '2021-01-01',
endDate: '2021-12-31'
Copy after login

});

//Listen to the query button click event
$('#query-btn').click(function() {

var range = $('#date-range').data('daterangepicker');

// 发送Ajax请求
$.ajax({
    type: 'GET',
    url: '/api/sales-data',
    data: {
        startDate: range.startDate.format('YYYY-MM-DD'),
        endDate: range.endDate.format('YYYY-MM-DD')
    },
    success: function(result) {
        // 处理查询结果
        drawChart(result.data);
    }
});
Copy after login

});

After receiving the query request in the background, Call the getSalesData method in ChannelSalesService to query sales data from the database and return it to the front-end page. The code is as follows:

@RestController
@RequestMapping("/api")
public class ApiController {

@Autowired
private ChannelSalesService channelSalesService;

/**
 * 获取不同渠道的销售数据
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @return 查询结果
 */
@GetMapping("/sales-data")
public Result getSalesData(@RequestParam("startDate")
                                   @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                           @RequestParam("endDate")
                                   @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
    List<ChannelSales> salesData = channelSalesService.getSalesData(startDate, endDate);
    return Result.success(salesData);
}
Copy after login

}

  1. Draw the chart

Once the sales data is obtained, you can use ECharts.js to draw the corresponding statistical chart. This article uses pie charts and bar charts to display the sales proportion and sales ranking of different channels.

(1) Pie chart

Let’s first look at the drawing of the pie chart. The pie chart is used to display the sales proportion of different channels. The code is as follows:

function drawChart (data) {

// 构造销售数据
var salesData = [];
var totalAmount = 0;
data.forEach(function(item) {
    salesData.push({
        name: item.channelName,
        value: item.salesAmount
    });
    totalAmount += item.salesAmount;
});

// 绘制饼图
var pieChart = echarts.init(document.getElementById('chart-1'));
var pieOption = {
    title: {
        text: '不同渠道销售占比',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    series: [
        {
            name: '渠道',
            type: 'pie',
            radius: '60%',
            data: salesData.sort(function(a, b) {
                return a.value - b.value;
            }),
            itemStyle: {
                normal: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            },
            label: {
                formatter: '{b} ({d}%)'
            }
        }
    ]
};
pieChart.setOption(pieOption);
Copy after login

}

(2) Histogram

The next step is to draw the histogram. The histogram is used to display the sales ranking of different channels. Code As shown below:

function drawChart(data) {

// 构造销售数据
var salesData = [];
data.forEach(function(item) {
    salesData.push({
        name: item.channelName,
        value: item.salesAmount
    });
});
salesData.sort(function(a, b) {
    return b.value - a.value;
});

// 绘制柱状图
var barChart = echarts.init(document.getElementById('chart-2'));
var barOption = {
    title: {
        text: '不同渠道销售排名',
        left: 'center'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        },
        formatter: '{b}: {c} 元'
    },
    xAxis: {
        type: 'category',
        data: salesData.map(function(item) {
            return item.name;
        }),
        axisLabel: {
            interval: 0,
            rotate: 45
        }
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name: '销售额',
            type: 'bar',
            data: salesData.map(function(item) {
                return item.value;
            }),
            itemStyle: {
                normal: {
                    color: function(params) {
                        var colorList = [
                            '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
                            '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570'
                        ];
                        return colorList[params.dataIndex % colorList.length];
                    }
                }
            }
        }
    ]
};
barChart.setOption(barOption);
Copy after login

}

3. Effect display

Finally, the achieved effect is displayed as shown in the figure below Display:

Figure 1 Sales proportion of different channels

Figure 2 Sales ranking of different channels

It can be seen intuitively from the chart that online channels account for the largest proportion of sales. At the same time, there is not much difference in sales between online and offline channels, but sales through social media channels are relatively low. This data helps companies understand business opportunities across different channels and make appropriate decisions.

4. Summary

This article introduces how to use ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison. In this way, not only can the sales data of different channels be visually displayed, but it can also help enterprises better understand the competition and business opportunities between channels, so as to make corresponding decisions. The specific implementation can be flexibly adjusted according to your own needs to adapt to different business scenarios.

The above is the detailed content of Use ECharts and Java interfaces to implement statistical chart design for multi-channel data comparison. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles