How to set color in a Livecharts graph

74 Views Asked by At

I'm creating an application with NET8 MAUI and I use LiveCharts. The result is quite good. When I create a graph, thought, the colors of the graph are quite random. For example, when I use this code

using System.Collections.Generic;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView;
using CommunityToolkit.Mvvm.ComponentModel;
using LiveChartsCore.SkiaSharpView.Extensions;
using LiveChartsCore.Defaults;
using LiveChartsCore.Measure;

namespace ViewModelsSamples.Pies.Gauge3;

public partial class ViewModel : ObservableObject
{
    public IEnumerable<ISeries> Series { get; set; } =
        GaugeGenerator.BuildSolidGauge(
            new GaugeItem(30, series => SetStyle("Vanessa", series)),
            new GaugeItem(50, series => SetStyle("Charles", series)),
            new GaugeItem(70, series => SetStyle("Ana", series)),
            new GaugeItem(GaugeItem.Background, series =>
            {
                series.InnerRadius = 20;
            }));

    public static void SetStyle(string name, PieSeries<ObservableValue> series)
    {
        series.Name = name;
        series.DataLabelsPosition = PolarLabelsPosition.Start;
        series.DataLabelsFormatter =
                point => $"{point.Coordinate.PrimaryValue} {point.Context.Series.Name}";
        series.InnerRadius = 20;
        series.RelativeOuterRadius = 8;
        series.RelativeInnerRadius = 8;
    }
}

and the related XAML here

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MauiSample.Pies.Gauge3.View"
             xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.Maui;assembly=LiveChartsCore.SkiaSharpView.Maui"
             xmlns:vms="clr-namespace:ViewModelsSamples.Pies.Gauge3;assembly=ViewModelsSamples">
    <ContentPage.BindingContext>
        <vms:ViewModel/>
    </ContentPage.BindingContext>
    <lvc:PieChart
        Series="{Binding Series}"
        InitialRotation="45"
        MaxAngle="270"
        MinValue="0"
        MaxValue="100">
    </lvc:PieChart>
</ContentPage>

the result is a nice graph like the following

enter image description here

How can I set my colors for the graph and each series?

2

There are 2 best solutions below

0
Jason On

from the docs

mySeries.Fill = Brushes.Red;
mySeries.Stroke = Brushes.Blue;
0
bto.rdz On

LiveCharts uses the colors in the current theme.

But you can also define your own, just set the Fill or Stroke properties.

series.Fill = new SolidColorPaint(SKColors.YellowGreen);

Here is an example: https://livecharts.dev/docs/Maui/2.0.0-rc2/samples.pies.gauge2