Web编程期末大作业Pro

用Echarts实现数据分析图表

做这个的时候,有三个图都挺好的,但饼状图这里 貌似 出了一点小意外。。
Web编程期末大作业Pro_第1张图片
但莫要慌张,我立即去请教了万能的助教老师,再加上自己的摸索,最终发现这个“[1]”是多余的,算是有惊无险地跨过了这个坎~

newdata.push({name: pattern.exec(element["x"][1]), value: element["y"]});

1、柱状图
前端代码:

$scope.histogram = function () {
        $scope.isShow = false;
        $http.get("/news/histogram")
            .then(
                function (res) {

                    if(res.data.message=='url'){
                        window.location.href=res.data.result;
                    }else {
                        let xdata = [], ydata = [], newdata;

                        var pattern = /\d{4}-(\d{2}-\d{2})/;
                        res.data.result.forEach(function (element) {
                            xdata.push(pattern.exec(element["x"])[1]);
                            ydata.push(element["y"]);
                        });
                        newdata = {"xdata": xdata, "ydata": ydata};

                        var myChart = echarts.init(document.getElementById('main1'));

                        var option = {
                            title: {
                                text: '球队的支持人数'
                            },
                            tooltip: {},
                            legend: {
                                data: ['人数']
                            },
                            xAxis: {
                                type: 'category',
                                name: '球队',
                                show: true,
                                data: ["Bucks","warriors","Lakers","Clippers","Celtics","Raptors","Heat","Thunder","Lone Rangers","Cavaliers"],
                                axisLabel: {
                                    rotate: 30,
                                    interval :0
                                }
                            },

                            yAxis: {
                                type: 'value',
                                name: '人数',
                                min: 0,
                                max: 1000,
                                interval:100,
                                axisLabel: {
                                    formatter: '{value}'
                                }
                            },
                            series: [{
                                name: '人数',
                                type: 'bar',

                                itemStyle: {
                                    normal: {
                                        color: function(params) {
                                            var colorList = [
                                                '#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',

                                                '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',

                                                '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                                            ];
                                            return colorList[params.dataIndex]
                                        },

                                        label: {
                                            show: true,
                                            position: 'top',
                                            formatter: '{c}'
                                        }
                                    }
                                },
                                barWidth: 50,
                                data: [630,750,900,690,720,500,450,580,530,400]
                            }]
                        myChart.setOption(option);
                    }
                },
                function (err) {
                    $scope.msg = err.data;
                });
   };

路由代码:

router.get('/histogram', function(request, response) {
    console.log(request.session['username']);

    //sql字符串和参数
    if (request.session['username']===undefined) {
        response.json({message:'url',result:'/index.html'});
    }else {
        var fetchSql = "select publish_date as x,count(publish_date) as y from fetches group by publish_date order by publish_date;";
        newsDAO.query_noparam(fetchSql, function (err, result, fields) {
            response.writeHead(200, {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": 0
            });
            response.write(JSON.stringify({message:'data',result:result}));
            response.end();
        });
    }
});

Web编程期末大作业Pro_第2张图片
2、饼状图
前端代码:

$scope.pie = function () {
        $scope.isShow = false;
        $http.get("/news/pie").then(
            function (res) {
                if(res.data.message=='url'){
                    window.location.href=res.data.result;
                }else {
                    let newdata = [];

                    var pattern = /责任编辑:(.+)/;
                    res.data.result.forEach(function (element) {
                        newdata.push({name: pattern.exec(element["x"]), value: element["y"]});
                    });

                    var myChart = echarts.init(document.getElementById('main1'));
                    var app = {};
                    option = null;
                    var option = {
                    title: {
                            text: '东方明珠游客来源分布图',  
                            y: 'top',
                            itemGap: 30,
                            backgroundColor: '#EEE',
                            textStyle: {
                            fontSize: 26,
                            fontWeight: 'bolder',
                            color: '#000080'
                            },
                            subtextStyle: {
                            fontSize: 18,
                            color: '#8B2323'
                            }
                        },

                        legend: {
                            y: 'center',
                            itemWidth: 24,  
                            itemHeight: 18,  
                            textStyle: {
                              color: '#666'  
                            },
                            itemGap: 30,
                            backgroundColor: '#eee',  
                            data: ['北京','上海','广东','湖南','四川','陕西']
                        },

                        series: [
                            {
                              name: '来源地',
                              type: 'pie',
                              radius: ['30%', '60%'], 
                              center: ['50%', '50%'],  
                              data: [
                                  {value:210, name:'北京'},
                                  {value:404, name:'上海'},
                                  {value:234, name:'广东'},
                                  {value:135, name:'湖南'},
                                  {value:148, name:'四川'},
                                  {value:120, name:'陕西'}
                              ],
                              itemStyle: {
                                emphasis: {
                                  shadowBlur: 10,
                                  shadowOffsetX: 0,
                                  shadowColor: 'rgba(30, 144, 255,0.5)'
                                }
                              },
                              labelLine: {
                                normal: {
                                  show: false  
                                }
                              },
                              label: {
                                normal: {
                                  position: 'inner',  
                                  formatter: '{c}'
                                }
                              }
                            }
                        ],

                        tooltip: {
                            trigger: 'item',
                            showDelay: 20,  
                            hideDelay: 20,   
                            backgroundColor: 'rgba(255,0,0,0.7)', 
                            textStyle: {
                              fontSize: '16px',
                              color: '#000' 
                            },
                            formatter: '{a} 
{b} : {c}个 ({d}%)' }, color: ['#7EC0EE', '#FF9F7F', '#FFD700', '#C9C9C9', '#E066FF', '#C0FF3E'] }; app.currentIndex = -1; setInterval(function () { var dataLen = option.series[0].data.length; myChart.dispatchAction({ type: 'downplay', seriesIndex: 0, dataIndex: app.currentIndex }); app.currentIndex = (app.currentIndex + 1) % dataLen; myChart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: app.currentIndex }); myChart.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: app.currentIndex }); }, 1000); if (option && typeof option === "object") { myChart.setOption(option, true); }; } }); };

路由代码:

router.get('/pie', function(request, response) {
    console.log(request.session['username']);

    if (request.session['username']===undefined) {
        response.json({message:'url',result:'/index.html'});
    }else {
        var fetchSql = "select author as x,count(author) as y from fetches group by author;";
        newsDAO.query_noparam(fetchSql, function (err, result, fields) {
            response.writeHead(200, {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": 0
            });
            response.write(JSON.stringify({message:'data',result:result}));
            response.end();
        });
    }
});

Web编程期末大作业Pro_第3张图片
3、折线图
前端代码:

$scope.line = function () {
        $scope.isShow = false;
        $http.get("/news/line").then(
            function (res) {
                if(res.data.message=='url'){
                    window.location.href=res.data.result;
                }else {
                    var myChart = echarts.init(document.getElementById("main1"));
                    option = {
                        title: {
                            text: '"综艺"该词在新闻中的出现次数随时间变化图'
                        },
                        xAxis: {
                            type: 'category',
                            data: Object.keys(res.data.result)
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [{
                            data: Object.values(res.data.result),
                            type: 'line',
                            itemStyle: {normal: {label: {show: true}}}
                        }],

                    };

                    if (option && typeof option === "object") {
                        myChart.setOption(option, true);
                    }
                }

            });
    };

路由代码:

router.get('/line', function(request, response) {
    console.log(request.session['username']);
    
    if (request.session['username']===undefined) {
        response.json({message:'url',result:'/index.html'});
    }else {
        var keyword = '综艺'; 
        var fetchSql = "select content,publish_date from fetches where content like'%" + keyword + "%' order by publish_date;";
        newsDAO.query_noparam(fetchSql, function (err, result, fields) {
            response.writeHead(200, {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": 0
            });
            response.write(JSON.stringify({message:'data',result:myfreqchangeModule.freqchange(result, keyword)}));
            response.end();
        });
    }
});

Web编程期末大作业Pro_第4张图片
4、词云
前端代码:

$scope.wordcloud = function () {
        $scope.isShow = false;
        $http.get("/news/wordcloud").then(
            function (res) {
                if(res.data.message=='url'){
                    window.location.href=res.data.result;
                }else {
                    var mainContainer = document.getElementById('main1');

                    var chart = echarts.init(mainContainer);

                    var data = [];
                    for (var name in res.data.result) {
                        data.push({
                            name: name,
                            value: Math.sqrt(res.data.result[name])
                        })
                    }

                    var maskImage = new Image();
                    maskImage.src = './images/logo.png';

                    var option = {
                        title: {
                            text: '所有新闻内容 jieba分词 的词云展示'
                        },
                        series: [{
                            type: 'wordCloud',
                            sizeRange: [12, 60],
                            rotationRange: [-90, 90],
                            rotationStep: 45,
                            gridSize: 2,
                            shape: 'circle',
                            maskImage: maskImage,
                            drawOutOfBound: false,
                            textStyle: {
                                normal: {
                                    fontFamily: 'sans-serif',
                                    fontWeight: 'bold',
                                    color: function () {
                                        return 'rgb(' + [
                                            Math.round(Math.random() * 160),
                                            Math.round(Math.random() * 160),
                                            Math.round(Math.random() * 160)
                                        ].join(',') + ')';
                                    }
                                },
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowColor: '#333'
                                }
                            },
                            data: data
                        }]
                    };

                    maskImage.onload = function () {
                        // option.series[0].data = data;
                        chart.clear();
                        chart.setOption(option);
                    };

                    window.onresize = function () {
                        chart.resize();
                    };
                }

            });

路由代码:

router.get('/wordcloud', function(request, response) {
    console.log(request.session['username']);

    if (request.session['username']===undefined) {
        // response.redirect('/index.html')
        response.json({message:'url',result:'/index.html'});
    }else {
        var fetchSql = "select content from fetches;";
        newsDAO.query_noparam(fetchSql, function (err, result, fields) {
            response.writeHead(200, {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": 0
            });
            response.write(JSON.stringify({message:'data',result:mywordcutModule.wordcut(result)}));
            response.end();
        });
    }
});

Web编程期末大作业Pro_第5张图片
到这里,这次的大作业就圆满结束了,
最后,感谢老师和助教对我不厌其烦的解答~

你可能感兴趣的:(Web编程期末大作业Pro)