Massimo Bortone
Massimo Bortone

Reputation: 621

Format time labels in charts_flutter time series chart

I have implemented a time series chart in my flutter app which displays energy data over time:

final List<charts.Series<TimeSeriesEnergy, DateTime>> seriesList = [
     new charts.Series<TimeSeriesEnergy, DateTime>(
        id: 'Energy',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (TimeSeriesEnergy p, _) => p.time,
        measureFn: (TimeSeriesEnergy p, _) => p.energy,
        data: data,
     )
];

final bool animate = true;

var chart = new charts.TimeSeriesChart<TimeSeriesEnergy>(
      seriesList,
      animate: animate,
);

I would like now to change the format of the labels on the xAxis, so that they display the time in hours and minutes, rather then the default local date time format. The example in the charts_flutter gallery suggest implementing a DateTimeFactory, but I have no idea on how to do this. Any suggestions are welcome :)

Upvotes: 6

Views: 7877

Answers (1)

Richard Heap
Richard Heap

Reputation: 51722

Add a DateTimeAxisSpec for your time (domain) axis.

var chart = new charts.TimeSeriesChart<TimeSeriesEnergy>(
  seriesList,
  domainAxis: new charts.DateTimeAxisSpec(
    tickFormatterSpec: new charts.AutoDateTimeTickFormatterSpec(
      day: new charts.TimeFormatterSpec(
        format: 'dd',
        transitionFormat: 'dd MMM',
      ),
    ),
  ),
  animate: animate,
);

In this example I changed the labels on my chart from the US default of "Jun 25", "27", "29" and "Jul 1" to "25 Jun", "27", "29" and "01 Jul" respectively.

You can change year, day and hour etc formatting too by adding additional TickFormatterSpecs for each of those.

The transitionFormat is used when the big value wraps, otherwise format is used. From my example, transitionFormat was used to format the first tick (so that you can see the month), but not the 27th or 29th as they are the same month. transitionFormat is again used for Jul 1st as the month has changed.

Upvotes: 10

Related Questions