我正在使用highcharts插件,我的目标是按小时绘制整天的图表。

如何将xAxis设置为使用12小时制(w / AM&PM),开始=>一天结束。或有一些选项可以间隔3小时。

例如我有todayyesterday的过滤器

我的数据如下所示(时间戳和值):

[ [1561593600000, 102.5], [1561658400000, 177.45] ]


这是我的完整脚本:

  $(function(){
    var moneySign = "$";

    Highcharts.setOptions({
      lang: {
        thousandsSep: ','
      }
    });

    // Sales Chart
    var SalesChart = Highcharts.chart('ba-chart-sales', {
      title: { text: '' },
      exporting: { enabled: false },
      subtitle: { text: '' },
      yAxis: {
        title: { text: '' },
        useHTML: true,
        labels: {
          formatter: function() {
            return moneySign + this.axis.defaultLabelFormatter.call({
              axis: this.axis,
              value: this.value
            });
          }
        }
      },
      xAxis: {
        // Default for 7days & 30days (will change for today||yesterday)
        type: 'datetime',
        dateTimeLabelFormats: { day: '%b %e' },
        tickInterval: 24 * 3600 * 1000 // interval of 1 day
      },
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        enabled:false
      },
      tooltip: {
        dateTimeLabelFormats: { day: '%B %e, %Y' },
        shared: true,
        useHTML: true,
        headerFormat: '{point.key}<div>',
        pointFormat: '<div style="background-color: #0549d1; height: 10px; width: 10px; border-radius: 50%; display: inline-block;"></div>' +
                     '<div style="margin-left: 5px; margin-top: 8px; width:30px; display: inline-block;"><b> ' + moneySign + '{point.y}</b></div>',
        footerFormat: '</div>',
        crosshairs: {
          color: '#ccc',
          className: 'chart-crosshair',
          dashStyle: 'solid',
          width: 1
        }
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false
          },
          marker: {
            enabled: false,
            symbol: 'circle'
          }
        }
      },
      series: [{
        tooltip: { xDateFormat: '%B %e, %Y' },
        showInLegend: false,
        name: '',
        data: []
      }],
      responsive: rules: [{
        condition: {
          maxWidth: 600
        },
        chartOptions: {
          legend: {
            layout: 'horizontal',
            align: 'center',
            verticalAlign: 'bottom'
          }
        }
      }],
      credits: { enabled: false }
    });


    // Initial
    var SalesChartExtremes = SalesChart.yAxis[0].getExtremes();

    // Change Cart Type `line` || `column`
    function reDrawChart(filter, chart) {
      var series  = SalesChart.series[0];
      var newType = ['today', 'yesterday'].includes(filter) ? 'column' : 'line';
      series.chart.addSeries({
        type: newType,
        name: series.name,
        color: series.color,
        data: series.options.data,
      }, false);
      series.remove();
    }

    // Get Offer Analytics Data
    function getAnalytics(filter=''){
      $.ajax({
        type: "GET",
        url: "<%= analytics_url %>",
        data: {chart_filter: filter},
        dataType: "JSON",
        success: function(data){
          var todayLocalDate = "<%= @local_time.strftime("%Y-%m-%d") %>".split('-').map(Number);
          var yesterdayLocalDate = "<%= @local_time.yesterday.strftime("%Y-%m-%d") %>".split('-').map(Number);

          if( ['30', '7', ''].includes(filter) ){
            var toolTipProp = { xDateFormat: '%B %e, %Y' };
            var pointIntervalProp = 24 * 3600 * 1000; // one day
            var pointStartProp = '';
            var chartType = 'line';
          }else{
            if (filter == 'today'){
              var pointStartProp = Date.UTC(todayLocalDate[0], todayLocalDate[1], todayLocalDate[2]);
            }else if (filter == 'yesterday'){
              var pointStartProp = Date.UTC(yesterdayLocalDate[0], yesterdayLocalDate[1], yesterdayLocalDate[2]);
            }
            var toolTipProp = { xDateFormat: '%B %e, %Y %I:%M%p' };
            var pointIntervalProp = 3600000 * 3; // 3 hours
            var chartType = 'column';
          }

          var markerEnabled = data.sales.length == 1
          var salesOpts = {
            tooltip: toolTipProp,
            data: data.sales,
            animation: { duration: 1000 },
            pointInterval: pointIntervalProp,
            pointStart: pointStartProp,
            crosshair: true,
            marker: {
              enabled: markerEnabled
            }
          }

          // Sets yAxis min & max values for empty result
          if(data.sales.length == 0){
            SalesChart.yAxis[0].setExtremes(0,100);
            SalesChart.yAxis[0].update({tickInterval: 20});
          }else{
            // return to previous categories based on data
            SalesChart.yAxis[0].setExtremes(SalesChartExtremes.min, SalesChartExtremes.max);
            SalesChart.yAxis[0].update({tickInterval: 500});
          }

          if(filter == 'today' || filter == 'yesterday'){
            var defaultTimeOpt = {
              tickInterval: 1,
              type: 'datetime',
              dateTimeLabelFormats: {
                millisecond: '%l:%M:%S.%L %P',
                second: '%l:%M:%S %P',
                minute: '%l:%M %P',
                hour: '%l:%M %P',
                day: '(%e. %b) %l:%M %P'
              }
            }
            SalesChart.xAxis[0].update(defaultTimeOpt, true);

          }else{
            // return to day options
            var defaultDayOpt = {
              type: 'datetime',
              dateTimeLabelFormats: { day: '%b %e' },
              tickInterval: 24 * 3600 * 1000 // interval of 1 day
            }

            SalesChart.xAxis[0].update(defaultDayOpt, false);
          }


          SalesChart.series[0].update(salesOpts, true);
          reDrawChart(filter, 'sales');

        },
        error: function(data) {
          flashError("Error getting analytics");
        }
      });
      return false;
    }

  });

// Call getAnalytics when select dropdown filter change (e.g. today, yesterday, lastweek ...)
getAnalytics();


目前的进展,

javascript - Highcharts将xAxis值设置为从上午12点开始到下午11点结束-LMLPHP

待办事项1:如果只有很少的数据,则没有数据应为0的时间(因此图表中仍存在进度)。

待办事项2:在xAxis中设置时间/小时,并可以选择小时间隔/时间间隔,例如3hours ... 12 AM、3AM、6AM...。

最佳答案

如果您已经有了价值,那么可以做类似的事情

xAxis: {
    labels: {
        //isPm() is a function that checks for am and pm of your timestamp
        format: '{value} ' + (isPm() ? "pm":"am")
    }
}


您还需要显示如何绘制图表,以便了解最佳的实现方式

关于javascript - Highcharts将xAxis值设置为从上午12点开始到下午11点结束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56729943/

10-13 01:46