如何绘制多图,然后在jquery flot中添加从mysql动态拉出的x轴标签

时间:2011-12-06 13:47:56

标签: jquery flot

我有一个工作的flot图,使用ajax从sql动态显示。我的问题是,我只能绘制一个系列。我的另一个问题是x轴标签。我希望动态地从sql日期字段中提取x轴标签。

这是我的ajax:

function getPlot() {
        $.ajax({
            url: "ajax/ajax-totalplot.php",
            dataType: "json",
            async: false,
            success: function(result) {
                d = result;
                //console.log(d);
            }
        });
        var data = d; // HOW CAN I ADD THE DATE FOR X-AXIS LABEL?
        var datasets = [ {
            "data" : data, lines: { show: true }, points: {show: true}
        }];
        $.plot('#Plot', datasets); 
    }

这是php

//run query    
    $sql = "SELECT date, bread, flower FROM `job` WHERE month(date) = 12 ORDER BY date";  

    $result = mysql_query($sql);

    while($row = mysql_fetch_array($result)) {
        $dd = date('d', strtotime($row['date'])); 
        $graphdata[] = array( (int)$dd, (int)$row['bread']);
    }


    print json_encode($graphdata); //HOW CAN I ADD THE FLOWER FIELD TO INCLUDE IN THE GRAPH AS WELL?

1 个答案:

答案 0 :(得分:3)

要获取第二个数据集,您需要生成另一个x,y值数组,然后将其添加到datasets

在PHP中:

   while($row = mysql_fetch_array($result)) {
        $dd = date('d', strtotime($row['date'])); 
        $graphdata[] = array( (int)$dd, (int)$row['bread']);
        $graphdata2[] = array( (int)$dd, (int)$row['flower']);
    }  

   print json_encode(array($graphdata,$graphdata2)); //maybe

然后在JS:

var datasets = [ 
{
      "data" : data[0], lines: { show: true }, points: {show: true}
},
{
      "data" : data[1], lines: { show: true }, points: {show: true}
} //second set of data is just another object in the datasets array
];
$.plot('#Plot', datasets);

要处理日期,请先检查this example。基本的交易是将xaxis模式设置为" time"然后将PHP中的日期作为Javascript时间戳提供给它。

因此,您需要在PHP中更改$dd变量的创建,然后在调用$.plot时添加一些选项:

//Change your SQL:
$sql = "SELECT unix_timestamp(date)*1000, bread, flower FROM `job` WHERE month(date) = 12 ORDER BY date";  

//change how you receive the date field:
$dd = $row['date']

//change how you call plot in JS:
$.plot('#Plot',dataset,{
   xaxis: {
     mode: "datetime"
   }
});