wiradikusuma
wiradikusuma

Reputation: 1919

charts_flutter: Different color for negative values in line chart

This code:

Widget _chart(ctx) =>
    TimeSeriesChart(_data(),
        customSeriesRenderers: [
            LineRendererConfig(
                customRendererId: 'filled',
                includeArea: true,
            ),
        ],
    );

List<Series<Point, DateTime>> _data() =>
    [
        Series<Point, DateTime>(
            id: 'Data',
            colorFn: (_, __) => MaterialPalette.blue.shadeDefault,
            data: store.data,
            domainFn: (Point p, _) => p.timestamp,
            measureFn: (Point p, _) => p.amount,
        )
            ..setAttribute(rendererIdKey, 'filled')
    ];

Produces this chart:

Sample chart

How do I make the negative filled area to be in different color e.g. red?

Bonus point if you can make the color to be in gradient (for both negative and positive).

Upvotes: 3

Views: 1625

Answers (1)

Roderik
Roderik

Reputation: 78

Not sure if you still need it since the question is from 2019... As far as I know making it gradient is (still) not possible. However I think its possible to change the area color by changing the color of the line based on the value. Like this:


List<Series<Point, DateTime>> _data() =>
          [
              Series<Point, DateTime>(
                  id: 'Data',
                  colorFn: (Point p, _) { 
                    if(p.amount < 0 || p.amount == 0){ 
                      return MaterialPalette.red.shadeDefault;
                    } else {
                      return MaterialPalette.blue.shadeDefault;
                    }
                  },
                  data: store.data,
                  domainFn: (Point p, _) => p.timestamp,
                  measureFn: (Point p, _) => p.amount,
              )
                  ..setAttribute(rendererIdKey, 'filled')
          ];

If the values goes from positive to negative, be sure to insert a fake 0 value. Since the lines are colored from point to point. Otherwhise you will see the blue line coming into the negative area.

Above works: screenshot area with two colors

Upvotes: 2

Related Questions