amcharts4中日期轴的最小值和最大值4

时间:2019-08-08 13:27:05

标签: charts amcharts amcharts4

我有一个带有日期轴的折线图,并且每天间隔30或15分钟显示数据。由于数据是动态的,因此在某些情况下,数据从中午12点左右或其他时间开始,因此x轴并非总是从00:00开始。同样,数据可能在午夜12:00之前结束。

我想始终显示dateAxis从00:00开始,然后进行一些修复,比如说每隔一两个小时标记一个标签,并在午夜12:00结束。我该怎么办?

我尝试使用DateAxis.min和DateAxis.max。但是这些仅接受数值。不知道如何将其设置为适当的数值来代表一天的开始和结束。

我还尝试设置DateAxis.extraMin和DateAxis.extraMax,但是它们正在处理百分比及其a,但是很难为动态数据找到合适的值。

This is how current graph renders

This is how i want to display (notice the empty labels at the start)

1 个答案:

答案 0 :(得分:0)

DateAxis对象中的min / max属性需要毫秒的时间戳。您可以使用来自JavaScript Date对象的getTime()的结果:

dateAxis.min = (new Date(2019,7,10)).getTime();
dateAxis.max = (new Date(2019,7,10,23)).getTime();

但是,没有一种方法可以明确地设置步骤。您可以调整minGridDistance来影响该步骤,仅此而已。唯一可以使用的解决方法是在每个时间戳上插入带有适当标签的指南(Axis Ranges),并禁用DateAxis的默认标签。

    range.date = new Date(2019, 7, 10, 0);
    range.grid.strokeOpacity = .5;
    range.grid.stroke = "#cecece";
    range.label.text = "00:00";

请注意,在这种情况下,轴不会调整标签的可见性,因此您可能还需要在范围标签上设置旋转角度。

下面的演示

// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);

// Add data
chart.data = generateData();

// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.startLocation = 0.5;
dateAxis.endLocation = 0.5;

// Create value axis
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = "value";
series.dataFields.dateX = "date";
series.name = "Sales";
series.strokeWidth = 3;
series.fillOpacity = 0.5;


dateAxis.baseInterval = {
  timeUnit: "minute",
  count: 15
}
dateAxis.renderer.grid.template.disabled = true;
dateAxis.renderer.labels.template.disabled = true;
dateAxis.min = (new Date(2019, 7, 10, 0)).getTime();
dateAxis.max = (new Date(2019, 7, 10, 23)).getTime();

generateRanges(dateAxis);

function generateRanges(axis) {
  var firstDate = new Date(2019, 7, 10, 0);
  for (var i = 0; i < 24; ++i) {
    var range = axis.axisRanges.create();
    var nextDate = new Date(firstDate);
    nextDate.setHours(i);
    range.date = nextDate;
    range.grid.strokeOpacity = .5;
    range.grid.stroke = "#cecece";
    range.label.text = ("0" + nextDate.getHours()).substr(-2) + ":" + ("0" + nextDate.getMinutes()).substr(-2);
    range.label.rotation = 90;
  }
}

function generateData() {
  var data = [];
  var firstDate = new Date(2019, 7, 10, 10);
  for (var i = 0; i < 32; ++i) {
    var nextDate = new Date(firstDate);
    nextDate.setMinutes(i * 15);
    data.push({
      date: nextDate,
      value: Math.floor(Math.random() * 15 + 5)
    })
  }
  return data;
}
<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv" style="width: 100%; height: 98vh;"></div>