Home > Java > javaTutorial > body text

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

王林
Release: 2023-12-17 13:43:44
Original
1085 people have browsed it

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!

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