Back to Livecharts2

Installation and first chart

docs/overview/1.2.install.md

2.1.0-dev-57011.4 KB
Original Source
<!-- To get help on editing this file, see https://github.com/beto-rodriguez/LiveCharts2/blob/master/docs/readme.md -->

Installation and first chart

Install from NuGet

You can [get LiveCharts from NuGet](https://www.nuget.org/packages/LiveChartsCore.SkiaSharpView.{{ platform_display_name }}). If you need more help to install a package from NuGet, please follow this guide.

{{ $"LiveChartsCore.SkiaSharpView.{platform_display_name}@{version}" | from_nuget }}

{{~ if blazor ~}} :::tip LiveCharts on Blazor WebAssembly needs the .NET WebAssembly build tools workload so SkiaSharp's native libs can be linked into your app's WASM bundle. Without it, the build fails with error LVC0001 and the runtime would otherwise crash with ReferenceError: Module is not defined on the first chart render (#2229).

Install it:

bash
dotnet workload install wasm-tools

Workloads are scoped to the SDK feature band, so a .NET SDK update — even a minor one that bumps the feature band (e.g. 10.0.1xx10.0.2xx) — can leave the workload missing again and re-trigger LVC0001. After updating the SDK, re-run the command above or dotnet workload update. ::: {{~ end ~}}

{{~ if winforms || wpf }} :::tip By default wpf and winforms projects target netx.0-windows but SkiaSharp 3 does not provide a build for that target, so NuGet will restore SkiaSharp dependencies using the .Net framework version. While that should not affect your app, you should consider to update the TargetFramework of your app and specify the min windows version, for example netx.0-windows10.0.19041, for more info see: https://github.com/Live-Charts/LiveCharts2/issues/1772. ::: {{ end ~}}

{{~ if winforms ~}} After the package is installed you should see the LiveCharts controls in your toolbox, drag a new CartesianChart control from your toolbox to the Form1 class.

If the control does not appear in your toolbox, try to rebuild your project and look for it again.

<p align="center"> </p>

Now go to the code behind of the Form1 class and edit the chart properties. {{~ end ~}}

{{~ if maui ~}} Register LiveCharts and SkiaSharp in your MauiProgram.cs file.

csharp
{{~ render "~/../samples/MauiSample/MauiProgram.cs" ~}}

{{~ end ~}}

First chart

The following example renders a basic chart in the UI.

{{~ render $"~/../samples/{platform_samples_folder}/General/FirstChart{view_extension}" ~}}

:::info If the chart is not showing, it is most likely that the layout where you placed the chart is hiding the control. LiveCharts controls do not have any size constraints, a quick fix is to explicitly set the size of the control (Width and Height), these related issues might help you #1483, #1581. :::

<p align="center"> </p>

{{~ if xaml ~}}

XAML and hot-reload

LiveCharts provides XAML-friendly counterparts to its core charting types. For example, the LineSeries<T> class has a matching XamlLineSeries type. All XAML types in the library use the Xaml prefix to clearly distinguish them from the non-visual LiveCharts objects.

These Xaml types are part of the UI framework — they live in the visual tree and behave like any other UI element. Because they're part of the visual layer, they support data bindings, styles, and other XAML features you'd expect when building user interfaces.

This means you can use hot-reload and designer previews to build charts interactively:

<p align="center"> </p>

{{~if !avalonia }} :::tip XAML designer support is limited due SkiaSharp restriction to run in the designer, but hot-reload is fully supported. ::: {{ end ~}}

This design allows developers to cleanly separate UI from business logic. In the following two examples, both approaches produce the same chart, but the first is cleaner: the ViewModel doesn’t depend on LiveCharts or SkiaSharp — it just exposes plain data.

Example 1

xml
<lvc:CartesianChart Grid.Row="2" SeriesSource="{Binding Data}">
    <lvc:CartesianChart.SeriesTemplate>
        <DataTemplate>
            <lvc:XamlColumnSeries
                SeriesName="{Binding Name}"
                Values="{Binding Values}"
                Fill="{Binding Color, Converter={StringToColorExampleConverter}}"/>
        </DataTemplate>
    </lvc:CartesianChart.SeriesTemplate>
</lvc:CartesianChart>
csharp
public partial class ViewModel
{
    public ChartData[] Data { get; set; } = [
        new("Juana",     [ 2, 5, 4 ], "#f00"),
        new("La cubana", [ 5, 4, 1 ], "#00f")
    ];
}

public class ChartData(string name, int[] points, string color)
{
    public string Name { get; set; } = name;
    public int[] Values { get; set; } = points;
    public string Color { get; set; } = color;
}

Example 2

xml
<lvc:CartesianChart Series={Binding Series}"/>
csharp
using SkiaSharp;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;

public partial class ViewModel
{
    public ISeries[] SeriesCollection { get; set; } = [
        new ColumnSeries<ObservableValue>
        {
            Name = "Juana",
            Values =[ new(2), new(5), new(4) ],
            Fill = new SolidColorPaint(new SKColor(255, 0, 0))
        },
        new ColumnSeries<ObservableValue>
        {
            Name = "la cubana",
            Values =[ new(5), new(4), new(1) ],
            Fill = new SolidColorPaint(new SKColor(0, 0, 255))
        }
    ];
}

{{~ end ~}}

Configure themes, fonts, RTL or mappers (Optional)

Optionally you can configure LiveCharts to add a theme, register a global font, add a mapper for a type or enable right to left tooltips and legends, lets create a new class and name it CustomLiveChartsExtensions, in this class define the AddLiveChartsAppSettings method extension to configure LiveCharts, all the next configuration is optional and overrides the default pre-defined settings in the library.

csharp
{{ render "~/../samples/ViewModelsSamples/LiveChartsAppSettings.cs" }}

{{~ if avalonia ~}} Now go to the Solution Explorer and browse for App.axaml.cs file, then edit it as follows:

csharp
{{ render "~/../samples/AvaloniaSample/App.axaml.cs" }}

{{~ end ~}}

{{~ if wpf ~}} Now go to the Solution Explorer and browse for App.xaml.cs file, then override the OnStartup method as follows:

csharp
{{ render "~/../samples/WPFSample/App.xaml.cs" }}

{{~ end ~}}

{{~ if winforms ~}} Now go to the Solution Explorer and browse for Program.cs file, then edit it as follows:

csharp
{{ render "~/../samples/WinFormsSample/Program.cs" }}

{{~ end ~}}

{{~ if uno ~}} Now go to the Solution Explorer and browse for UnoApp.Shared/App.xaml.cs file, then edit it as follows:

csharp
{{ render "~/../samples/UnoPlatformSample/UnoPlatformSample/App.xaml.cs" }}

{{~ end ~}}

{{~ if winui ~}} Now go to the Solution Explorer and browse for App.xaml.cs file, then edit it as follows:

csharp
{{ render "~/../samples/WinUISample/WinUISample/App.xaml.cs" }}

{{~ end ~}}

{{~ if blazor ~}}

Now go to the solution explorer, browse for the App.razor file, then edit it as follows:

{{ render "~/../samples/BlazorSample/App.razor" }}

{{~ end ~}}

{{~ if maui ~}} Now go to the Solution Explorer and browse for MauiProgram.cs file, then find UseLiveCharts() method and chain the AddLiveChartsAppSettings() method at our LiveCharts configuration section:

csharp
.UseLiveCharts(config => config
    .AddLiveChartsAppSettings())

{{~ end ~}}

Enable hardware acceleration

LiveCharts supports hardware accelerated views via SkiaSharp, by default the library is not hardware accelerated, this is because as today the GPU views by SkiaSharp are not as stable as the CPU views.

:::tip On Avalonia or Uno with the SkiaRenderer enabled, the LiveCharts settings for GPU/CPU control or VSync are ignored, since this is handled by Avalonia/Uno, LiveCharts just draws as the UI framework wants. It is normally already using hardware acceleration, but completely handled by the UI framework. :::

{{~ if blazor ~}} :::tip Blazor is the exception: UseGPU defaults to true because the WebGL-backed SKGLView produces desktop-quality charts, while raster mode (SKCanvasView) is visibly lower quality.

You will want to opt out of WebGL when:

  • You render many charts on the same page. Browsers cap the number of live WebGL contexts (~8 in Chromium); past that limit older charts go blank with a Too many active WebGL contexts. Oldest context will be lost. warning in the console.
  • Your environment cannot create a WebGL context at all (headless browsers without a software WebGL fallback, sandboxed iframes that block the WebGL feature, etc.).

Opt out before the first chart is rendered (i.e. in App.razor's OnInitialized):

csharp
LiveCharts.Configure(c => c
    .HasRenderingSettings(s => s.UseGPU = false));

::: {{~ end ~}}

GPU improves the time it takes to render a frame, which results in smoother and more efficient animations, but as today, there are some known issues when using the SkiaSharp hardware accelerated views (specially when disposing/re-creating the controls), you can turn on hardware acceleration, the recommendation is to update SkiaSharp to the latest available version, then test if it works correctly for your case.

If you face an issue with the hardware accelerated views, ensure to identify if the issue belongs to SkiaSharp or LiveCharts; If the issue occurs on both CPU and GPU render modes, then the issue is most likely a LiveCharts issue, if it only happens when GPU is on, then it is most likely an issue with the hardware accelerated views of SkiaSharp.

csharp
{{ render "~/../samples/ViewModelsSamples/LiveChartsRenderSettings.cs" }}

Finally chain the render settings we just created at our LiveCharts configuration section:

{{~ if maui ~}}

csharp
// ...
.UseLiveCharts(config => config
    .AddLiveChartsAppSettings()
    .AddLiveChartsRenderSettings())

{{~ else ~}}

csharp
LiveCharts.Configure(c => c
    .AddLiveChartsAppSettings()
    .AddLiveChartsRenderSettings());

{{~ end ~}}

Advanced rendering

SkiaSharp makes it easy to take the library to Android, iOS, Windows, MacOS, Tizen, Linux and the Web, but on advanced scenarios you can build your own backend, for example in the next example we use DirectX11 via Vortice.Windows to render our chart. This gives us full control over the rendering pipeline, this has some benefits such as:

  • Improved performance.
  • Potentially smaller exe files since we no longer need the Skia natives.
  • Potentially better AOT builds.

You can find the Vortice sample at the GitHub repo, it does not support all the features in the library, this example is just to demonstrate that LiveCharts dependency on SkiaSharp is optional; We can connect the library to any drawing engine.