Search code examples
c#wpflivecharts

Customize starting index in LiveChart


I am trying to draw a simple LineSeries with LiveChart. Because computer/array index by default starts with 0, and human (non-programmer) starts counting with 1, so I like to display the value's index starting with 1 (i.e. index+1), but could not figure out how to do this.

I read the LiveChart documentation on Types and Configurations, and tried to get a mapper of index + 1 into the SeriesCollection but I get an invalid argument error: cannot convert from 'LiveCharts.Configurations.CartesianMapper' to 'LiveCharts.Definitions.Series.ISeriesView'

var mapper1 = new CartesianMapper<double>()
        .X((value, index) => index + 1) 
        .Y((value, index) => value); 

sc = new SeriesCollection
{
    new LineSeries
    {
        Values = new ChartValues<double>()  {1,2,3,4,1,2,3,4,1,2},
    },
    mapper1
};

enter image description here


Solution

  • I can answer this only because I have had to tinker with LiveCharts myself, not because I got it from their documentation (although I did find it embedded here)

    If you want to set a mapper specifically for one series, you can add it to the delcaration as follows:

    var mapper1 = new CartesianMapper<double>()
            .X((value, index) => index + 1) 
            .Y((value, index) => value); 
    
    sc = new SeriesCollection(mapper1)
    {
        new LineSeries
        {
            Values = new ChartValues<double>()  {1,2,3,4,1,2,3,4,1,2},
        }
    };
    

    Alternatively, there is a way to set a global mapper for specific data types, e.g. if you're using MeasureModel:

    var mapper = Mappers.Xy<MeasureModel>()
                .X(model => model.DateTime.Ticks)   //use DateTime.Ticks as X
                .Y(model => model.Value);           //use the value property as Y
    
    //lets save the mapper globally.
    Charting.For<MeasureModel>(mapper);
    

    That example is from here.