search
HomeJavajavaTutorialECharts and Java interface: How to quickly implement statistical charts such as line charts, bar charts, pie charts, etc.

ECharts and Java interface: How to quickly implement statistical charts such as line charts, bar charts, pie charts, etc.

ECharts and Java interface: How to quickly implement statistical charts such as line charts, bar charts, pie charts, etc., need specific code examples

With the advent of the Internet era, data Analytics are becoming increasingly important. Statistical charts are a very intuitive and powerful display method. Charts can display data more clearly, allowing people to better understand the connotation and patterns of the data. In Java development, we can use ECharts and Java interfaces to quickly display various statistical charts.

ECharts is a data visualization chart library based on HTML5 Canvas developed by Baidu. It can easily draw a variety of charts, including line charts, bar charts, pie charts, etc. The Java interface is a technology that enables back-end data to interact with front-end display, and can pass data to the front-end through Java code. Next, we will introduce how to use ECharts and Java interfaces to quickly display various statistical charts.

  1. Implementing a line chart

A line chart is a chart that represents data trends by connecting data points. In ECharts, we can implement a line chart through the following code:

// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));

// 指定图表的配置项和数据
var option = {
    title: {
        text: '折线图'
    },
    tooltip: {},
    legend: {
        data:['销量']
    },
    xAxis: {
        data: ["周一","周二","周三","周四","周五","周六","周日"]
    },
    yAxis: {},
    series: [{
        name: '销量',
        type: 'line',
        data: [5, 20, 36, 10, 20, 30, 40]
    }]
};

// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);

The above code shows how to use ECharts to implement a line chart. We can set various parameters of the chart in the option object, such as the title of the chart, the labels of the x-axis and y-axis, etc. By passing data to the data attribute in the series, the corresponding data can be displayed in the chart. Finally use the setOption method to render the chart.

How to implement a line chart in Java? We can pass data to the front end through the following Java code:

@RequestMapping("/echarts")
@ResponseBody
public Map<String,Object> echarts(){
    List<String> categories = new ArrayList<String>();
    categories.add("周一");
    categories.add("周二");
    categories.add("周三");
    categories.add("周四");
    categories.add("周五");
    categories.add("周六");
    categories.add("周日");

    List<Integer> data = new ArrayList<Integer>();
    data.add(5);
    data.add(20);
    data.add(36);
    data.add(10);
    data.add(20);
    data.add(30);
    data.add(40);

    Map<String,Object> result = new HashMap<String,Object>();
    result.put("categories",categories);
    result.put("data",data);

    return result;
}

In the above code, we create a Map object and put the x-axis and y-axis data into categories and data respectively. Then return the Map object to the front end.

Finally, add the following JS code to the front-end code to complete the back-end data rendering of the line chart:

$.ajax({
    url: '/echarts',
    type: 'get',
    success: function(data){
        var categories = data.categories;
        var data = data.data;
        var option = {
            title: {
                text: '折线图'
            },
            tooltip: {},
            legend: {
                data:['销量']
            },
            xAxis: {
                data: categories
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'line',
                data: data
            }]
        };
        myChart.setOption(option);
    },
    error: function(){
        alert('error');
    }
});
  1. Implementing the bar chart

A bar chart is a chart used to compare the size of different categories of data. In ECharts, we can implement histograms through the following code:

// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));

// 指定图表的配置项和数据
var option = {
    title: {
        text: '柱状图'
    },
    tooltip: {},
    legend: {
        data:['销量']
    },
    xAxis: {
        data: ["周一","周二","周三","周四","周五","周六","周日"]
    },
    yAxis: {},
    series: [{
        name: '销量',
        type: 'bar',
        data: [5, 20, 36, 10, 20, 30, 40]
    }]
};

// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);

The above code shows how to use ECharts to implement histograms. Similar to the line chart, we can set various parameters of the chart in the option object, such as the title of the chart, the labels of the x-axis and y-axis, etc. At the same time, we only need to set the type attribute to 'bar' to convert the line chart into a bar chart.

How to implement a histogram in Java? We can pass data to the front end through the following Java code:

@RequestMapping("/echarts")
@ResponseBody
public Map<String,Object> echarts(){
    List<String> categories = new ArrayList<String>();
    categories.add("周一");
    categories.add("周二");
    categories.add("周三");
    categories.add("周四");
    categories.add("周五");
    categories.add("周六");
    categories.add("周日");

    List<Integer> data = new ArrayList<Integer>();
    data.add(5);
    data.add(20);
    data.add(36);
    data.add(10);
    data.add(20);
    data.add(30);
    data.add(40);

    Map<String,Object> result = new HashMap<String,Object>();
    result.put("categories",categories);
    result.put("data",data);

    return result;
}

In the above code, we create a Map object and put the x-axis and y-axis data into categories and data respectively. Then return the Map object to the front end. Add the following JS code to the front-end code to complete the back-end data rendering of the histogram:

$.ajax({
    url: '/echarts',
    type: 'get',
    success: function(data){
        var categories = data.categories;
        var data = data.data;
        var option = {
            title: {
                text: '柱状图'
            },
            tooltip: {},
            legend: {
                data:['销量']
            },
            xAxis: {
                data: categories
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: data
            }]
        };
        myChart.setOption(option);
    },
    error: function(){
        alert('error');
    }
});
  1. Implementing the pie chart

The pie chart is a way to represent A chart of data proportions. In ECharts, we can implement pie charts through the following code:

// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));

// 指定图表的配置项和数据
var option = {
    title: {
        text: '饼图',
        subtext: '数据来自网络'
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
        orient: 'vertical',
        left: 10,
        data: ['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
    },
    series: [
        {
            name: '访问来源',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '30',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: [
                {value: 335, name: '直接访问'},
                {value: 310, name: '邮件营销'},
                {value: 234, name: '联盟广告'},
                {value: 135, name: '视频广告'},
                {value: 1548, name: '搜索引擎'}
            ]
        }
    ]
};

// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);

The above code shows how to use ECharts to implement pie charts. Similar to line charts and bar charts, we can set various parameters of the chart in the option object, such as the title of the chart, the labels of the x-axis and y-axis, etc. By passing data to the data attribute in the series, the corresponding data can be displayed in the chart. Note that the pie chart data here needs to meet the format corresponding to the value and name, such as {value:335, name:'direct access'}.

How to implement a pie chart in Java? We can pass data to the front end through the following Java code:

@RequestMapping("/echarts")
@ResponseBody
public List<Map<String,Object>> echarts(){
    List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();

    Map<String,Object> data1 = new HashMap<String,Object>();
    data1.put("value",335);
    data1.put("name","直接访问");
    result.add(data1);

    Map<String,Object> data2 = new HashMap<String,Object>();
    data2.put("value",310);
    data2.put("name","邮件营销");
    result.add(data2);

    Map<String,Object> data3 = new HashMap<String,Object>();
    data3.put("value",234);
    data3.put("name","联盟广告");
    result.add(data3);

    Map<String,Object> data4 = new HashMap<String,Object>();
    data4.put("value",135);
    data4.put("name","视频广告");
    result.add(data4);

    Map<String,Object> data5 = new HashMap<String,Object>();
    data5.put("value",1548);
    data5.put("name","搜索引擎");
    result.add(data5);

    return result;
}

In the above code, we create a Map array with 5 elements and store the values ​​and names in the Map. Then return the Map array to the front end. Add the following JS code to the front-end code to complete the back-end data rendering of the pie chart:

$.ajax({
    url: '/echarts',
    type: 'get',
    success: function(data){
        var legendData = [];
        var seriesData = [];
        $.each(data,function(index,item){
            legendData.push(item.name);
            seriesData.push(item);
        });

        var option = {
            title: {
                text: '饼图',
                subtext: '数据来自网络'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: legendData
            },
            series: [
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '30',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: seriesData
                }
            ]
        };
        myChart.setOption(option);
    },
    error: function(){
        alert('error');
    }
});

Summary:

Through the above examples, we can find that ECharts and Java interfaces are used to display statistics The chart is very simple. You only need to call the Java interface in the front-end code to obtain the data, and then pass it to the option object of ECharts. In the Java interface, the data needs to be encapsulated into a collection object such as Map or List first, and then returned to the front end. Naturally, it is more convenient to use Spring Boot. The combination of ECharts and Java interface can adapt to various development models with front-end and back-end separation.

The above is the detailed content of ECharts and Java interface: How to quickly implement statistical charts such as line charts, bar charts, pie charts, etc.. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor