后端加前端Echarts绘图示例全流程(折线图,饼图,柱状图) ...

打印 上一主题 下一主题

主题 917|帖子 917|积分 2751

本文将向导读者通过一个完整的Echarts绘图示例项目,演示如何联合后端技能(使用Spring Boot框架)和前端技能(使用Vue.js或React框架)来实现数据可视化。我们将实现折线图、饼图和柱状图三种常见的数据展示方式,通过具体的代码和步骤让读者把握从零开始搭建项目到展示图表的全过程。
  开发环境

后端
SpringBoot  2.6.13
Mybatis-Plus 3.4.3
前端
原生JavaScript
前期预备

数据库创建语句
  1. CREATE TABLE sales_data (
  2.     id INT AUTO_INCREMENT PRIMARY KEY,
  3.     month VARCHAR(7) NOT NULL,
  4.     amount DECIMAL(10, 2) NOT NULL
  5. );
复制代码

具体实现 

实体类
  1. @Data
  2. @TableName("sales_data")
  3. public class SalesRecord {
  4.    
  5.     @TableId(type = IdType.AUTO)
  6.     private Long id;
  7.    
  8.     private String month;
  9.    
  10.     private Double amount;
  11. }
复制代码
Mapper层
  1. @Mapper
  2. public interface SalesRecordMapper extends BaseMapper<SalesRecord> {
  3.     // 自定义查询方法,根据月份范围查询销售记录
  4.     @Select("SELECT * FROM sales_data WHERE month BETWEEN #{startMonth} AND #{endMonth}")
  5.     List<SalesRecord> findByMonthBetween(@Param("startMonth") String startMonth, @Param("endMonth") String endMonth);
  6. }
复制代码
Service层
  1. public interface SalesRecordService {
  2.     List<SalesRecord> getAllSalesRecords();
  3.     List<SalesRecord> getSalesRecordsByMonthRange(String startMonth, String endMonth);
  4. }
复制代码
Impl层
  1. @Service
  2. public class SalesRecordServiceImpl extends ServiceImpl<SalesRecordMapper, SalesRecord> implements SalesRecordService {
  3.     @Resource
  4.     private SalesRecordMapper salesRecordMapper;
  5.     @Override
  6.     public List<SalesRecord> getAllSalesRecords() {
  7.         return list();
  8.     }
  9.     @Override
  10.     public List<SalesRecord> getSalesRecordsByMonthRange(String startMonth, String endMonth) {
  11.         // 实现根据月份范围查询的逻辑,使用 repository 或者自定义 SQL 查询数据库
  12.         return salesRecordMapper.findByMonthBetween(startMonth, endMonth);
  13.     }
  14. }
复制代码
Controller层
  1. @RestController
  2. @RequestMapping("/api/sales")
  3. public class SalesRecordController {
  4.     private final SalesRecordService salesRecordService;
  5.     @Autowired
  6.     public SalesRecordController(SalesRecordService salesRecordService) {
  7.         this.salesRecordService = salesRecordService;
  8.     }
  9.     @GetMapping("/records")
  10.     public List<SalesRecord> getAllSalesRecords() {
  11.         return salesRecordService.getAllSalesRecords();
  12.     }
  13.     @GetMapping("/recordsByMonthRange")
  14.     public List<SalesRecord> getSalesRecordsByMonthRange(
  15.             @RequestParam("startMonth") String startMonth,
  16.             @RequestParam("endMonth") String endMonth) {
  17.         return salesRecordService.getSalesRecordsByMonthRange(startMonth, endMonth);
  18.     }
  19. }
复制代码
前端页面

创建路径:src/main/resources/static/sales_bar_chart.html
柱形图(包含按照日期分页)
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="UTF-8">
  5.   <title>Sales Data Visualization</title>
  6.   <!-- 引入 ECharts -->
  7.   <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  8.   <!-- 引入 jQuery -->
  9.   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  10. </head>
  11. <body>
  12. <!-- 时间范围选择表单 -->
  13. <label for="startMonth">开始月份:</label>
  14. <input type="month" id="startMonth" name="startMonth">
  15. <label for="endMonth">结束月份:</label>
  16. <input type="month" id="endMonth" name="endMonth">
  17. <button onclick="updateChart()">更新图表</button>
  18. <!-- 图表展示 -->
  19. <div id="chart" style="width: 800px; height: 600px;"></div>
  20. <script>
  21.   // 初始化页面时渲染默认图表
  22.   renderDefaultChart();
  23.   // 渲染默认图表
  24.   function renderDefaultChart() {
  25.     var xhr = new XMLHttpRequest();
  26.     xhr.open('GET', 'http://localhost:8099/api/sales/records');
  27.     xhr.onload = function () {
  28.       if (xhr.status === 200) {
  29.         var salesData = JSON.parse(xhr.responseText);
  30.         renderChart(salesData);
  31.       } else {
  32.         console.error('Failed to fetch sales data:', xhr.statusText);
  33.       }
  34.     };
  35.     xhr.onerror = function () {
  36.       console.error('Request failed.');
  37.     };
  38.     xhr.send();
  39.   }
  40.   // 更新图表函数,根据用户选择的时间范围发送请求
  41.   function updateChart() {
  42.     var startMonth = document.getElementById('startMonth').value;
  43.     var endMonth = document.getElementById('endMonth').value;
  44.     var xhr = new XMLHttpRequest();
  45.     xhr.open('GET', `http://localhost:8099/api/sales/recordsByMonthRange?startMonth=${startMonth}&endMonth=${endMonth}`);
  46.     xhr.onload = function () {
  47.       if (xhr.status === 200) {
  48.         var salesData = JSON.parse(xhr.responseText);
  49.         renderChart(salesData);
  50.       } else {
  51.         console.error('Failed to fetch sales data:', xhr.statusText);
  52.       }
  53.     };
  54.     xhr.onerror = function () {
  55.       console.error('Request failed.');
  56.     };
  57.     xhr.send();
  58.   }
  59.   // 渲染 ECharts 图表
  60.   function renderChart(data) {
  61.     var chart = echarts.init(document.getElementById('chart'));
  62.     var months = data.map(function (item) {
  63.       return item.month;
  64.     });
  65.     var amounts = data.map(function (item) {
  66.       return item.amount;
  67.     });
  68.     var option = {
  69.       title: {
  70.         text: 'Monthly Sales Amount'
  71.       },
  72.       tooltip: {},
  73.       xAxis: {
  74.         data: months
  75.       },
  76.       yAxis: {},
  77.       series: [{
  78.         name: 'Sales Amount',
  79.         type: 'bar',
  80.         data: amounts
  81.       }]
  82.     };
  83.     chart.setOption(option);
  84.   }
  85. </script>
  86. </body>
  87. </html>
复制代码
 

饼图
创建路径:src/main/resources/static/pie-chart-ajax.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="UTF-8">
  5.   <title>Sales Data Pie Chart</title>
  6.   <!-- 引入 ECharts -->
  7.   <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  8. </head>
  9. <body>
  10. <!-- 定义一个具有一定尺寸的 div,用于渲染图表 -->
  11. <div id="pieChart" style="width: 600px; height: 400px;"></div>
  12. <script>
  13.   // 使用 AJAX 请求后端数据
  14.   var xhr = new XMLHttpRequest();
  15.   xhr.open('GET', 'http://localhost:8099/api/sales/records'); // 修改为实际的后端 API 路径
  16.   xhr.onload = function () {
  17.     if (xhr.status === 200) {
  18.       var salesData = JSON.parse(xhr.responseText);
  19.       renderPieChart(salesData);
  20.     } else {
  21.       console.error('Failed to fetch sales data:', xhr.statusText);
  22.     }
  23.   };
  24.   xhr.onerror = function () {
  25.     console.error('Request failed.');
  26.   };
  27.   xhr.send();
  28.   // 渲染 ECharts 饼图
  29.   function renderPieChart(data) {
  30.     var pieChart = echarts.init(document.getElementById('pieChart'));
  31.     // 构建饼图所需的数据格式
  32.     var pieData = data.map(function(item) {
  33.       return {
  34.         name: item.month,
  35.         value: item.amount
  36.       };
  37.     });
  38.     // 配置饼图的选项
  39.     var option = {
  40.       title: {
  41.         text: '销售数据分布'
  42.       },
  43.       tooltip: {
  44.         trigger: 'item',
  45.         formatter: '{a} <br/>{b} : {c} ({d}%)'
  46.       },
  47.       legend: {
  48.         orient: 'vertical',
  49.         left: 'left',
  50.         data: data.map(function(item) { return item.month; }) // 设置图例数据
  51.       },
  52.       series: [
  53.         {
  54.           name: '销售数据',
  55.           type: 'pie',
  56.           radius: '55%',
  57.           center: ['50%', '60%'],
  58.           data: pieData // 使用从后端获取的数据
  59.         }
  60.       ]
  61.     };
  62.     // 使用配置项设置图表
  63.     pieChart.setOption(option);
  64.   }
  65. </script>
  66. </body>
  67. </html>
复制代码

折线图
创建路径:src/main/resources/static/sales_long_chart.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Sales Data Line Chart</title>
  6.     <!-- 引入 ECharts -->
  7.     <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  8.     <!-- 引入 jQuery -->
  9.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  10. </head>
  11. <body>
  12. <!-- 定义一个具有一定尺寸的 div,用于渲染图表 -->
  13. <div id="lineChart" style="width: 800px; height: 600px;"></div>
  14. <script>
  15.     // 使用 AJAX 请求后端数据
  16.     var xhr = new XMLHttpRequest();
  17.     xhr.open('GET', 'http://localhost:8099/api/sales/records'); // 修改为实际的后端 API 路径
  18.     xhr.onload = function () {
  19.         if (xhr.status === 200) {
  20.             var salesData = JSON.parse(xhr.responseText);
  21.             renderLineChart(salesData);
  22.         } else {
  23.             console.error('Failed to fetch sales data:', xhr.statusText);
  24.         }
  25.     };
  26.     xhr.onerror = function () {
  27.         console.error('Request failed.');
  28.     };
  29.     xhr.send();
  30.     // 渲染 ECharts 折线图
  31.     function renderLineChart(data) {
  32.         var lineChart = echarts.init(document.getElementById('lineChart'));
  33.         // 构建折线图所需的数据格式
  34.         var xAxisData = data.map(function(item) {
  35.             return item.month;
  36.         });
  37.         var seriesData = data.map(function(item) {
  38.             return item.amount;
  39.         });
  40.         // 配置折线图的选项
  41.         var option = {
  42.             title: {
  43.                 text: '销售数据趋势'
  44.             },
  45.             tooltip: {
  46.                 trigger: 'axis',
  47.                 formatter: '{a} <br/>{b} : {c}'
  48.             },
  49.             xAxis: {
  50.                 type: 'category',
  51.                 data: xAxisData // 设置 X 轴数据
  52.             },
  53.             yAxis: {
  54.                 type: 'value'
  55.             },
  56.             series: [{
  57.                 name: '销售额',
  58.                 type: 'line',
  59.                 data: seriesData // 设置折线图数据
  60.             }]
  61.         };
  62.         // 使用配置项设置图表
  63.         lineChart.setOption(option);
  64.     }
  65. </script>
  66. </body>
  67. </html>
复制代码
希望本文对你有所帮助。如果你有任何疑问或发起,接待在批评区留言讨论。Happy coding!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

西河刘卡车医

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表