0

可以在同一页面上插入两个图表吗?我从数据库中提取数据,然后在页面上绘制图表。这是我用于绘制图形的伪代码,我更改了 id 元素但我只显示了第一个图形,而第二个不起作用。

<? $res_app = mysql_query("SELECT ... ") 
...
?>
<div id="graph"></div>
<pre id="code" class="prettyprint linenums">
Morris.Donut({
  element: 'graph',
  data: [
    {value: 70, label: 'foo'},
    {value: 15, label: 'bar'},
    {value: 10, label: 'baz'},
    {value: 5, label: 'A really really long label'}
  ],
  formatter: function (x) { return x + "%"}
});
</pre>

<? $res_app = mysql_query("SELECT ... ") 
...
?>
<div id="graph1"></div>
<pre id="code" class="prettyprint linenums">
Morris.Donut({
  element: 'graph1',
    data: [
      {value: 50, label: 'foo', formatted: 'at least 50%' },
      {value: 25, label: 'bar', formatted: 'approx. 25%' },
      {value: 20, label: 'baz', formatted: 'approx. 20%' },
      {value: 5, label: 'A really really long label', formatted: 'at most 5%' }
    ],
   formatter: function (x, data) { return data.formatted; }
});
</pre>
4

1 回答 1

0

我想出了以下解决方案,以便在一页上呈现多个图表:

var $lineChart = $('.line-chart-js');
if($lineChart.length) {
    $lineChart.each(function (index, element) {
        var chartData = JSON.parse($(this).attr('data-chart'));
        new Morris.Line({
            // ID of the element in which to draw the chart.
            element: $(this),
            // Chart data records -- each entry in this array corresponds to a point on
            // the chart.
            data: chartData,
            // The name of the data record attribute that contains x-values.
            xkey: $(this).attr('data-x'),
            // A list of names of data record attributes that contain y-values.
            ykeys: [$(this).attr('data-y')],
            // Labels for the ykeys -- will be displayed when you hover over the
            // chart.
            labels: [$(this).attr('data-label')]
        });
    });
}

HTML 看起来像这样:

<div class="line-chart-js" data-x='xkey' data-y='ykey' data-label='label' data-chart='<?php echo json_encode($yourArray); ?>'></div>

这样您就可以重用您的课程,而不必为每个图表编写单独的 javascript。

于 2016-04-19T12:39:12.750 回答