首页 > 解决方案 > 如何更改 Flutter 中的 Y 或 X 轴标签?

问题描述

我正在尝试将我的 Y 轴标签从 60,000 之类的数字更改为 60k。目前,我正在使用Charts_Flutter依赖项。

这是我的图表的样子:

在此处输入图像描述

这是我的代码的样子:

            child: charts.TimeSeriesChart(
              series,
              animate: true,
              domainAxis: new charts.DateTimeAxisSpec(
                tickFormatterSpec: new charts.AutoDateTimeTickFormatterSpec(
                  day: new charts.TimeFormatterSpec(
                    format: 'dd',
                    transitionFormat: 'dd MMM',
                  ),
                ),
              ),
              primaryMeasureAxis: new charts.NumericAxisSpec(
                renderSpec: new charts.GridlineRendererSpec(

                  // Tick and Label styling here.
                  labelStyle: new charts.TextStyleSpec(
                    fontSize: 10, // size in Pts.
                    color: charts.MaterialPalette.black
                  ),
                )
              ),
              defaultRenderer: charts.LineRendererConfig(
                includeArea: true,
                includeLine: true,
                includePoints: true,
                strokeWidthPx: 0.5,
                radiusPx: 1.5
              ),
              dateTimeFactory: const charts.LocalDateTimeFactory(),
              behaviors: [
                charts.PanAndZoomBehavior(),
                charts.SelectNearest(
                  eventTrigger: charts.SelectionTrigger.tap
                ),
                charts.LinePointHighlighter(
                  symbolRenderer: CustomCircleSymbolRenderer(size: size),
                ),
              ],
              selectionModels: [
                charts.SelectionModelConfig(
                type: charts.SelectionModelType.info,
                changedListener: (charts.SelectionModel model) {
                  if(model.hasDatumSelection) {
                    final tankVolumeValue = model.selectedSeries[0].measureFn(model.selectedDatum[0].index).round();
                    final dateValue = model.selectedSeries[0].domainFn(model.selectedDatum[0].index);
                    CustomCircleSymbolRenderer.value = '$dateValue \n $tankVolumeValue L';
                }
              })
            ]),
          ),
        );

欢迎任何关于如何更改标签的想法。

标签: fluttergraphflutter-layoutflutter-dependencies

解决方案


charts_flutter你可以指定一个使用NumberFormat他们的BasicNumericTickFormatterSpec类(这似乎根本不是基本的)。

然后将此格式化程序类提供给您的图表

下面我使用NumberFormat.compact()了将 60,000 变成 60K 的方法。

    /// Formatter for Y-axis numbers using [NumberFormat] compact
    ///
    /// Used in the [NumericAxisSpec] below.
    final myNumericFormatter =
        BasicNumericTickFormatterSpec.fromNumberFormat(
          NumberFormat.compact() // ← your format goes here
        );

    return TimeSeriesChart(seriesList,
        animate: animate,
        // Use myNumericFormatter on the primaryMeasureAxis
        primaryMeasureAxis: NumericAxisSpec(
            tickFormatterSpec: myNumericFormatter // ← pass your formatter here
        ),

这是使用上述内容的完整运行示例:

import 'package:charts_flutter/flutter.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class ChartFormatPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chart Format'),
      ),
      body: Center(
        child: ChartCustomYAxis.withSampleData(),
      )
    );
  }
}

class ChartCustomYAxis extends StatelessWidget {
  final List<Series> seriesList;
  final bool animate;

  ChartCustomYAxis(this.seriesList, {this.animate});

  /// Creates a [TimeSeriesChart] with sample data and no transition.
  factory ChartCustomYAxis.withSampleData() {
    return ChartCustomYAxis(
      _createSampleData(),
      // Disable animations for image tests.
      animate: false,
    );
  }


  @override
  Widget build(BuildContext context) {
    /// Formatter for Y-axis numbers using [NumberFormat] compact
    ///
    /// Used in the [NumericAxisSpec] below.
    final myNumericFormatter =
        BasicNumericTickFormatterSpec.fromNumberFormat(
          NumberFormat.compact() // ← your format goes here
        );

    return TimeSeriesChart(seriesList,
        animate: animate,
        // Use myNumericFormatter on the primaryMeasureAxis
        primaryMeasureAxis: NumericAxisSpec(
            tickFormatterSpec: myNumericFormatter // ← pass your formatter here
        ),

        /// Customizes the date tick formatter. It will print the day of month
        /// as the default format, but include the month and year if it
        /// transitions to a new month.
        ///
        /// minute, hour, day, month, and year are all provided by default and
        /// you can override them following this pattern.
        domainAxis: DateTimeAxisSpec(
            tickFormatterSpec: AutoDateTimeTickFormatterSpec(
                day: TimeFormatterSpec(
                    format: 'd', transitionFormat: 'MM/dd/yyyy'))));
  }

  /// Create one series with sample hard coded data.
  static List<Series<MyRow, DateTime>> _createSampleData() {
    final data = [
      MyRow(DateTime(2017, 9, 25), 6000),
      MyRow(DateTime(2017, 9, 26), 8000),
      MyRow(DateTime(2017, 9, 27), 6000),
      MyRow(DateTime(2017, 9, 28), 9000),
      MyRow(DateTime(2017, 9, 29), 11000),
      MyRow(DateTime(2017, 9, 30), 15000),
      MyRow(DateTime(2017, 10, 01), 25000),
      MyRow(DateTime(2017, 10, 02), 33000),
      MyRow(DateTime(2017, 10, 03), 27000),
      MyRow(DateTime(2017, 10, 04), 31000),
      MyRow(DateTime(2017, 10, 05), 23000),
    ];

    return [
      Series<MyRow, DateTime>(
        id: 'Cost',
        domainFn: (MyRow row, _) => row.timeStamp,
        measureFn: (MyRow row, _) => row.cost,
        data: data,
      )
    ];
  }
}

/// Sample time series data type.
class MyRow {
  final DateTime timeStamp;
  final int cost;
  MyRow(this.timeStamp, this.cost);
}

上面的例子是从这里偷来的,修改为 show NumberFormat.compact

在此处输入图像描述


推荐阅读