首页 > 代码库 > highcharts 图表操作实例

highcharts 图表操作实例

这个是前段时间做的一个项目模块,实现内容是调查问卷,如:

1:你的性别?

2:你的年龄?

。。。。。。

后台根据提交的内容,通过图表显示比例出来

废话就不说了,贴上代码:

注意,我项目是mvc框架

前台代码:

<strong><span style="font-size:14px;"><div class="panel-body">
        <table width="100%" class="table-hover">
            <tbody>
                @if (Model != null && Model.Any())
                {
                    var i = 0;
                    foreach (var kvp in Model)
                    {
                        i++;
                        <tr>
                            <td>
                                <div class="row">
                                    <div class="col-md-6">
                                        <section class="panel">
                                            <header class="panel-heading"> 问题 @i:@kvp.Value  </header>
                                            <!--图表-->
                                            <div class="panel-body">
                                                <div <span style="color:#ff0000;">id='pic_@kvp.Key' class="pieChart" </span>qname="@kvp.Value" qid="@kvp.Key"></div>
                                            </div>
                                        </section>
                                    </div>
                                    <div class="col-md-6">
                                        <section class="panel">
                                            <!--图表-->
                                            <header class="panel-heading">  <span class="tools pull-right"> <a class="fa fa-chevron-down" href="javascript:;"></a> <a class="fa fa-cog" href="javascript:;"></a> <a class="glyphicon glyphicon-dashboard" href="javascript:;"></a> </span> </header>
                                            <div class="panel-body">
                                                <div <span style="color:#ff0000;">id='pillar_@kvp.Key' class="pillarChart"</span> qname="@kvp.Value" qid="@kvp.Key"></div>
                                            </div>
                                        </section>
                                    </div>
                                </div>

                            </td>
                        </tr>
                    }
                    @Html.Hidden("pid", (int)ViewBag.ProId)
                }
                else
                {
                    <tr><td>当前结果分析还未有数据!</td></tr>
                }
            </tbody>
        </table>
    </div></span></strong>

大家要注意我红色标记的地方,是关键的地方,

js代码:

<strong><span style="font-size:14px;">   <!--图表highcharts-->
    <script src="http://cdn.pisen.com.cn/pmc/plugins/highcharts/highcharts.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //饼图2
           <span style="color:#ff0000;"> $(".pieChart")</span>.each(function () {
                ShowPie($(this).attr("qid"));
            });
            //柱形
            <span style="color:#ff0000;">$(".pillarChart")</span>.each(function () {
                ShowPillar($(this).attr("qid"), $(this).attr("qname"));
            });
        });
        //获取饼图数据
        function ShowPie(qid) {
            var postdata = { qid: qid, pid: $("#pid").val() };
            $.post('@Url.Action("QueryPic", "ResultChart")', postdata, function (data) {
                GetPie(eval(data), qid);
            }, "script");
        }
        //获取柱形数据
        function ShowPillar(qid, qname) {
            var postdata = { qid: qid, pid: $("#pid").val() };
            $.post('@Url.Action("QueryPillar", "ResultChart")', postdata, function (data) {
                GetPillar(eval("[" + data + "]"), qid, qname);
            }, "json");
        }
        //获取饼图数据
        function GetPie(newdata, qid) {
            //执行饼图显示方法
           <span style="color:#ff0000;"> $('#pic_' + qid)</span>.highcharts({
                chart: {
                    borderWidth: 0,
                    plotShadow: false,
                    plotBorderWidth: 0
                },
                colors: ['#f66930', '#ecb939', '#48abee', '#f58d48', '#3dbd5b', '#81e0d6', '#80edbb'],
                title: {
                    text: ''
                },
                tooltip: {
                    pointFormat: '{series.name}: {point.percentage:.1f}%'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            color: '#000000',
                            connectorColor: '#000000',
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                        }
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Browser share',
                    data: newdata
                }]

            });
        }

        //获取柱形图
        function GetPillar(newdata, qid, qname) {
           <span style="color:#ff0000;"> $('#pillar_' + qid)</span>.highcharts({
                chart: {
                    type: 'column'
                },
                colors: ['#f66930', '#ecb939', '#48abee', '#f58d48', '#3dbd5b', '#81e0d6', '#80edbb'],
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    categories: ['' + qname + '']
                },

                yAxis: {
                    title: {
                        text: null
                    },
                    min: 0,
                    lineWidth: 1,
                    lineColor: '#c0c0c0',
                    labels: {
                        formatter: function () {
                            return this.value;
                        }
                    }
                },
                tooltip: {
                    crosshairs: true,
                    shared: true
                },
                plotOptions: {
                    column: {
                        pointPadding: 0.2,
                        borderWidth: 0
                    }
                },
                series: newdata
            });
        }
    </script></span></strong>

后台方法:后台注意是返回生成图表的格式数据

    <strong><span style="font-size:14px;">    /// <summary>
        /// 获取饼图数据
        /// </summary>
        /// <param name="qid">问题主iD</param>
        /// <param name="pid">问题ID</param>
        /// <returns>获取饼图数据</returns>
        public ActionResult QueryPic(int? qid, int? pid)
        {
            if (!pid.HasValue && !qid.HasValue) return JavaScript("");

            var chartList = _resultChartBo.QueryChartByQuestId(pid.Value);
            var strbBuilder = new StringBuilder();

            strbBuilder.Append("[");

            foreach (var dic in chartList.Where(m => m.QId == qid.Value).ToList())
            {
                strbBuilder.AppendFormat("['{0}',{1}],", dic.OptionName, dic.Con);
            }

            var strPic = strbBuilder.ToString().Substring(0, strbBuilder.ToString().Length - 1);
            strPic += "]";

            return JavaScript(strPic);
        }

        /// <summary>
        /// 获取柱形图数据
        /// </summary>
        /// <param name="qid">问题主iD</param>
        /// <param name="pid">问题ID</param>
        /// <returns>获取柱形图数据</returns>
        public ActionResult QueryPillar(int? qid, int? pid)
        {
            if (!pid.HasValue && !qid.HasValue) return Json("");

            var chartList = _resultChartBo.QueryChartByQuestId(pid.Value);
            var strBuild = new StringBuilder();
            var categories = new StringBuilder();
            var categ = string.Empty;
            if (null != chartList && chartList.Count > 0)
            {
                foreach (var dic in chartList.Where(m => m.QId == qid.Value).ToList())
                {
                    strBuild.Append("{");
                    strBuild.AppendFormat("name: '{0}',data: [{1}]", dic.OptionName, dic.Con);
                    //strBuild.Append("{");
                    //strBuild.AppendFormat("y: {0},marker: ", dic.Con);
                    //strBuild.Append("{symbol: 'url(../plugins/highcharts/img/st-0159.gif)'}");
                    //strBuild.Append("}");
                    //strBuild.Append("]");
                    strBuild.Append("},");

                    categories.AppendFormat("'{0}',", dic.QName);
                }
                if (categories.Length > 0)
                {
                    categ = categories.ToString().Substring(0, categories.ToString().Length - 1);
                }
                ViewBag.Categories = categ;
                //ViewData["Categories"] = categ;
            }

            //去掉最后一个字符
            var strPillar = string.Empty;
            if (strBuild.Length > 0)
            {
                strPillar = strBuild.ToString().Substring(0, strBuild.ToString().Length - 1);
            }
            return Json(strPillar);
        }</span></strong>

   highcharts插件下载地址:highcharts.rar


效果图:



highcharts 图表操作实例