hAxis中的Google折线图月份标签不正确

时间:2020-03-18 09:16:35

标签: javascript charts google-visualization linechart

我有一个包含3条线的动画折线图。

提琴:

https://jsfiddle.net/8b3czfuq/

我在带有h月份月份标签的折线图上显示每日明智数据。

showData() {
    this.form.components[0].label = 'Again Changed';
    this.triggerRefresh.emit({
    form: this.form
});
}
google.charts.load('current', {
  packages: ['corechart']
});
google.setOnLoadCallback(prepareChartData);

function prepareChartData(){
  var chartData = new google.visualization.DataTable();
  chartData.addColumn('date', 'Date');
  chartData.addColumn('number', 'Total');
  chartData.addColumn('number', 'Dogs');
  chartData.addColumn('number', 'Cats');
  title = 'My Chart';

  var options = {
    title: title,
    curveType: 'function',
    legend: {position: 'bottom', alignment: 'start'},
    colors: ['#003f5c', '#ffa600', '#665191', '#f95d6a'],

    annotations: {
      alwaysOutside: true,
      textStyle: {
        color: 'black',
        fontSize: 11
      },
    },
    hAxis: {
      format: 'MMM yy',
      viewWindowMode: "explicit",
    },
    vAxis: {
      minValue: 0,
      viewWindowMode: "explicit",
      viewWindow: { min: 0 },
      title: ''
    },
    titleTextStyle: {
      color:'#3a3a3a',
      fontSize:24,
      bold:false
      // fontName: "Segoe UI"
      },
    bar: {groupWidth: '95%'},
    bars: 'horizontal'
  };

  var chartDivId = "chart_div";
  var chart = new google.visualization.LineChart(document.getElementById(chartDivId));
  var rawData =[];

   var chart_object = { "Feb 20": {monthLabel: "Feb", chartArray:[{'date': "2020-2-12", 'total': "5", 'cats': "10", 'dogs': "10"},{'date': "2020-2-13", 'total': "15", 'cats': "20", 'dogs': "20"}]}, "Mar 20": {monthLabel: "Mar", chartArray:[{'date': "2020-3-10", 'total': "5", 'cats': "10", 'dogs': "10"},{'date': "2020-03-11", 'total': "15", 'cats': "30", 'dogs': "30"}]}};

  $.each(chart_object, function(i, chartobject) {
 	$.each(  chartobject.chartArray, function( chartIndex , chartValue ){

    date = chartValue['date'];
    total = parseInt(chartValue['total']);
    catscount = parseInt(chartValue['cats']);
    dogscount = parseInt(chartValue['dogs']);
    catspercentage = 0;
    catspercentageAnnotation = catscount+",  percent "+catspercentage+"%";
    dogsspercentage = 0;
    dogsspercentageAnnotation = dogscount+",  percent "+dogsspercentage+"%";

    rawData.push([ new Date(date), total, {v: catscount, f: catspercentageAnnotation}, {v: dogscount, f: dogsspercentageAnnotation}]);
	  });
  });

  var counter = 0;
  drawChart();

  function drawChart() {
    if(counter < rawData.length){
      chartData.addRow(rawData[counter]);

      // build x-axis ticks to prevent repeated labels
      var dateRange = chartData.getColumnRange(0);
      var ticks = [];
      var dateTick = dateRange.min;
      while (dateTick.getTime() <= dateRange.max.getTime()) {
        ticks.push(dateTick);
        dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 2, 0);
      }
      options.hAxis.ticks = ticks;

      chart.draw(chartData, options);
      counter++;
      window.setTimeout(drawChart, 1000);
    }
  }
}

此图表存在一些问题。

  1. 我有2月和3月月份的数据。但是hAxis标签中仅显示Feb标签。预期结果是它应该显示与对象中的日期相对应的所有月份标签。

  2. haxis月标签从左端开始,而最后一个月在最右端。我想在折线图中显示该月数据从何处开始的标签。例如,假设我有四月以前的数据,即使折线图中的四月数据在标签位置之前开始,横坐标中的四月标签也显示在右端。

  3. 对于haxis中的第一个标签,我也想显示日期。在这种情况下,2020-2-12是最小值数据。因此,在轴上应显示2月12日20日,所有其他标签应仅为MMM yy。

有人可以帮我做以上3个修复程序吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

在月初显示日期标签,
需要使用每月的第一天...

dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 1, 1);  // first day

当前代码使用每月的最后一天(基于另一个问题的数据)

dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 2, 0);  // last day

下一步,为了以不同的格式显示第一个日期,
我们可以使用对象符号({})进行勾号,
其中v:是刻度的值,f:是格式化的值

在这里,我们使用日期格式化程序来更改第一个刻度的格式

  // build x-axis ticks to prevent repeated labels
  var dateFormat = new google.visualization.DateFormat({
    pattern: 'yyyy-MM-dd'
  });
  var dateRange = chartData.getColumnRange(0);
  var ticks = [];
  var dateTick = dateRange.min;
  while (dateTick.getTime() <= dateRange.max.getTime()) {
    if (ticks.length === 0) {
      // format first tick
      ticks.push({
        v: dateTick,
        f: dateFormat.formatValue(dateTick)
      });
    } else {
      ticks.push(dateTick);
    }
    dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 1, 1);
  }

请参阅以下工作片段...

google.charts.load('current', {
  packages: ['corechart']
});
google.setOnLoadCallback(prepareChartData);

function prepareChartData(){
  var chartData = new google.visualization.DataTable();
  chartData.addColumn('date', 'Date');
  chartData.addColumn('number', 'Total');
  chartData.addColumn('number', 'Dogs');
  chartData.addColumn('number', 'Cats');
  title = 'My Chart';

  var options = {
    title: title,
    curveType: 'function',
    legend: {position: 'bottom', alignment: 'start'},
    colors: ['#003f5c', '#ffa600', '#665191', '#f95d6a'],

    annotations: {
      alwaysOutside: true,
      textStyle: {
        color: 'black',
        fontSize: 11
      },
    },
    hAxis: {
      format: 'MMM yy',
      viewWindowMode: "explicit",
    },
    vAxis: {
      minValue: 0,
      viewWindowMode: "explicit",
      viewWindow: { min: 0 },
      title: ''
    },
    titleTextStyle: {
      color:'#3a3a3a',
      fontSize:24,
      bold:false
      // fontName: "Segoe UI"
      },
    bar: {groupWidth: '95%'},
    bars: 'horizontal'
  };

  var chartDivId = "chart_div";
  var chart = new google.visualization.LineChart(document.getElementById(chartDivId));
  var rawData =[];

   var chart_object = { "Feb 20": {monthLabel: "Feb", chartArray:[{'date': "2020-2-12", 'total': "5", 'cats': "10", 'dogs': "10"},{'date': "2020-2-13", 'total': "15", 'cats': "20", 'dogs': "20"}]}, "Mar 20": {monthLabel: "Mar", chartArray:[{'date': "2020-3-10", 'total': "5", 'cats': "10", 'dogs': "10"},{'date': "2020-03-11", 'total': "15", 'cats': "30", 'dogs': "30"}]}};

  $.each(chart_object, function(i, chartobject) {
 	$.each(  chartobject.chartArray, function( chartIndex , chartValue ){

    date = chartValue['date'];
    total = parseInt(chartValue['total']);
    catscount = parseInt(chartValue['cats']);
    dogscount = parseInt(chartValue['dogs']);
    catspercentage = 0;
    catspercentageAnnotation = catscount+",  percent "+catspercentage+"%";
    dogsspercentage = 0;
    dogsspercentageAnnotation = dogscount+",  percent "+dogsspercentage+"%";

    rawData.push([ new Date(date), total, {v: catscount, f: catspercentageAnnotation}, {v: dogscount, f: dogsspercentageAnnotation}]);
	  });
  });

  var counter = 0;
  drawChart();

  function drawChart() {
    if(counter < rawData.length){
      chartData.addRow(rawData[counter]);

      // build x-axis ticks to prevent repeated labels
      var dateFormat = new google.visualization.DateFormat({
        pattern: 'yyyy-MM-dd'
      });
      var dateRange = chartData.getColumnRange(0);
      var ticks = [];
      var dateTick = dateRange.min;
      while (dateTick.getTime() <= dateRange.max.getTime()) {
        if (ticks.length === 0) {
          // format first tick
          ticks.push({
            v: dateTick,
            f: dateFormat.formatValue(dateTick)
          });
        } else {
          ticks.push(dateTick);
        }
        dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 1, 1);
      }
      options.hAxis.ticks = ticks;

      chart.draw(chartData, options);
      counter++;
      window.setTimeout(drawChart, 1000);
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript" ></script>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <div id="chart_div"></div>