Search code examples
c#livecharts

c# Live Chart Line Different Color


I have two time series, first is every daily price and second is some day's price. I want to one line but I awant to paint the some day's price. I found that link but I don't understand how to do it.

link: https://github.com/Live-Charts/Live-Charts/issues/162#issuecomment-232700608

my code:

var dayConfig = Mappers.Xy < ChartModel > ().X(dayModel =>dayModel.DateTime.Ticks).Y(dayModel =>dayModel.Value);

SeriesCollection = new SeriesCollection(dayConfig) {
  new LineSeries {
    Title = hisse1,
    Values = ChartModelList.AsChartValues(),
  },
};

Formatter = value =>new DateTime((long) value).ToString("dd.MM.yyyy");
DataContext = this;

Solution

  • You can define series colors either in XAML or in your data model.

    XAML

    <wpf:CartesianChart Series="{Binding SeriesCollection}>
      <wpf:CartesianChart.SeriesColors>
        <wpf:ColorsCollection>
          <Color>Yellow</Color>
          <Color>Green</Color>
        </wpf:ColorsCollection>
      </wpf:CartesianChart.SeriesColors>
    </wpf:CartesianChart>
    

    C#

    You can generally set attributes like Fill, Stroke, StrokeThickness and StrokeDashArray to customize the series' color.

    // Draw a sine
    var chartValues = new ChartValues<Point>();
    for (int x = 0; x < 361; x++)
    {
      var point = new Point() {X = x, Y = Math.Sin(x * Math.PI / 180)};
      chartValues.Add(point);
    }
    
    this.SeriesCollection = new SeriesCollection
    {
      // Set the line series color directly on the series object
      new LineSeries
      {
        Title = "Yellow Series",
        Values = chartValues,
        Fill = Brushes.Yellow,
        Stroke = Brushes.Blue
      },
      // Or use a Mapper which offers more flexibility e.g. allowing conditional coloring
      new LineSeries
      {
        Title = "Mixed Color Series",
        Configuration = new CartesianMapper<Point>()
          .X(point => point.X)
          .Y(point => point.Y)
          .Stroke(point => point.X > 50 ? Brushes.Red : Brushes.LightGreen)
          .Fill(point => point.X > 50 ? Brushes.Red : Brushes.LightGreen),
        Values = chartValues
      }
    };