How to customize the segment color based on the Y value in Xamarin.Forms Charts
This article explains how to set the different colors to its segment based on its Y value in the Xamarin.Forms Chart.
SfChart provides the support for customizing its appearance by allowing to apply the predefined colors to the segment as per its arranging order and also defining the desired color to its segments.
Consider the use-case is to apply the green color for the segment’s Y value is lesser than 30 and also apply the red color for the segment’s Y value is greater than 40. It has been achieved by setting the Palette as Custom and defined the range consider color collection to the CustomBrushes of the series’s color model as shown in the following code.
[C#]
… ColumnSeries series= new ColumnSeries(); series.ItemsSource = viewModel.Data; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.ColorModel.Palette = ChartColorPalette.Custom; series.ColorModel.CustomBrushes = Colors; chart.Series.Add(series); …
Color is a type of ChartColorCollection. Color is defined based on the Y value added to it.
[C#]
public ChartColorCollection Colors { get; set; } . . . Colors = new ChartColorCollection(); foreach (var item in viewModel.Data) { if (item.YValue <= 29) { Colors.Add(Color.Green); } else if (item.YValue > 29 && item.YValue <=32) { Colors.Add(Color.Blue); } else if (item.YValue => 40) { Colors.Add(Color.Red); } } . . . .
Output:
Figure: Set different color based on the Y value.
See also:
How to apply the custom font to Xamarin.Forms chart
How to set the opacity of the chart series
How to increase or decrease the width of Column series