在指定的日期将数据放入图表中

时间:2019-01-20 15:50:49

标签: javascript php mysql highcharts

我目前正在使用高图制作月度图表,并且想在指定的日期输出数据,该怎么办?我只是在学习如何使用动态数据来使用图表。

这是我的代码:

    <?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"projects");

    /* Getting purchases table data */
    $sql = "SELECT SUM(total_cost) as count FROM purchases
            GROUP BY MONTH(`date`) ORDER BY `date`";
    $purchases = mysqli_query($link,$sql);
    $purchases = mysqli_fetch_all($purchases,MYSQLI_ASSOC);
    $purchases = json_encode(array_column($purchases, 'count'),JSON_NUMERIC_CHECK);


    /* Getting sales table data */
    $sql = "SELECT SUM(product_total) as count FROM confirm_order_product
            GROUP BY MONTH(`date`) ORDER BY `date`";
    $sales = mysqli_query($link,$sql);
    $sales = mysqli_fetch_all($sales,MYSQLI_ASSOC);
    $sales = json_encode(array_column($sales, 'count'),JSON_NUMERIC_CHECK);



?>
<script type="text/javascript">

/*series: [{
        name: 'Sales',
          data: data_sales,
         // pointStart: Date.UTC(2018, 1, 1),
         //  pointInterval: 24 * 3600 * 1000

      },{
         name: 'Purchases',
        data: data_purchases
     //   pointStart: Date.UTC(2018, 1, 1),
     //    pointInterval: 24 * 3600 * 1000
   }]*/

$(function () {


    var data_sales = <?php echo $sales; ?>;
    var data_purchases = <?php echo $purchases; ?>;


    $('#container').highcharts({
        chart: {
            type: 'line'
        },
        title: {
            text: 'Monthly Sales and Purchases'
        },
        xAxis: {
            //categories: ['January','February','March','April','May','June','July','August','Sepmtember','October','November','December']
            type: 'datetime',
           dateTimeLabelFormats: {


      month: '%b ',

           },
           title: {
               text: 'Date'
           }
        },

        series: [{
            name: 'Sales',
            data: data_sales

        }, {
            name: 'Purchases',
            data: data_purchases
        }]
    });
});

我有9月,11月,12月的数据,其余的都没有,运行代码时显示的是Jan,Feb和Marc,而不是实际日期。

1 个答案:

答案 0 :(得分:0)

如果您的数据不包含日期,则必须在图表选项中进行指定。第一种方法是使用datetime轴并设置适当的pointStart和pointInterval:

plotOptions: {
    series: {
      pointStart: Date.UTC(2018, 8, 1),
      pointInterval: 30 * 24 * 3600 * 1000,
    }
}

演示: https://jsfiddle.net/BlackLabel/o4cq132m/

第二种方法是使用这样的类别:

xAxis: {
    type: 'category',
    categories: ['Sepmtember','October','November','December'],
    title: {
      text: 'Date'
    }
}

演示: https://jsfiddle.net/BlackLabel/h9ykq7mf/3/



当您的数据包含日期时,您可以像这样提供它们:

  xAxis: {
    type: 'datetime'
  },
  series: [{
    data: [
      [1535752800000, 122], // [timestamp in milliseconds, value]
      [1538344800000, 131],
      [1541026800000, 111],
      [1543618800000, 120]
    ]
  }]

演示:
https://jsfiddle.net/BlackLabel/zhynkgoa/

API参考:
https://api.highcharts.com/highcharts/series.line.data