Plotting in C#.Net (Part2 - LiveCharts2)
Amir Doosti
Software Engineer | 20+ Years of Expertise | .NET, Industrial Automation with Beckhoff, Microservices Architecture
LiveCharts is a versatile and modern charting library that supports a variety of charts and visualizations with smooth animations and real-time data updates. For WinForms development, LiveCharts can be used to create interactive and visually appealing charts like line, bar, pie, scatter, and more.
In this article, we'll go through the key features of LiveCharts and learn how to implement some common types of charts in a WinForms application.
By the way, in my GitHub you can find a WinForm project which shows some of most important features of this library in action in the following link:
Setting Up LiveCharts in a WinForms Project
Creating a Basic Line Chart, Bar Chart and Pie Chart
A line chart is one of the most common chart types, and LiveCharts makes it easy to create and customize.
Add Required Namespaces:
using LiveChartsCore.SkiaSharpView.WinForms;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore;
using LiveChartsCore.Defaults;
Add a Line Chart to Your Form: In the Form's constructor, create a new line chart and add it to the form.
public Form1()
{
InitializeComponent();
// Create a new line chart
var lineChart = new CartesianChart
{
Dock = DockStyle.Fill // Fill the form with the chart
};
// Set the series collection for the line chart
lineChart.Series = new ISeries[]
{
new LineSeries<double>
{
Values = new double[] { 3, 5, 7, 9, 4, 6, 8 },
Fill = null, // No fill for the line area
LineSmoothness = 0 // Set to 0 for straight lines
}
};
// Optionally, configure the axes
lineChart.XAxes = new Axis[]
{
new Axis { Labels = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul" } }
};
// Add the chart to the form
Controls.Add(lineChart);
}
Creating a Bar Chart
Bar charts are another common chart type, and LiveCharts supports them with similar ease.
var barChart = new CartesianChart
{
Dock = DockStyle.Fill
};
barChart.Series = new ISeries[]
{
new ColumnSeries<double>
{
Values = new double[] { 10, 20, 30, 40, 50, 60, 70 },
Stroke = new SkiaSharp.SKColor(0, 0, 255), // Optional: Customize the bar color
Fill = new SkiaSharp.SKColor(0, 0, 255, 128) // Optional: Customize fill color
}
};
// Configure the axes if needed
barChart.YAxes = new Axis[]
{
new Axis { Labeler = value => value.ToString("C") } // Format as currency
};
Controls.Add(barChart);
Adding a Pie Chart
Pie charts are useful for showing proportional data, and you can set them up similarly to line and bar charts.
var pieChart = new PieChart
{
Dock = DockStyle.Fill
};
pieChart.Series = new ISeries[]
{
new PieSeries<double> { Values = new double[] { 30 }, Name = "Category A" },
new PieSeries<double> { Values = new double[] { 40 }, Name = "Category B" },
new PieSeries<double> { Values = new double[] { 30 }, Name = "Category C" }
};
Controls.Add(pieChart);
Showing and Formatting the Legend
LiveCharts allows you to customize legends to make them more informative or visually appealing.
Displaying the Legend:
chart.LegendPosition = LiveChartsCore.Measure.LegendPosition.Right;
Formatting the Legend:
Customize the legend text using the LegendTextPattern property.
var lineSeries = new LineSeries<double>
{
Values = new double[] { 3, 5, 7, 9, 4, 6, 8 },
LegendText = "My Data Series"
};
Changing Legend Alignment:
Control the alignment of the legend within the chart.
chart.LegendAlignment = LiveChartsCore.Measure.LegendAlignment.BottomCenter;
Styling the Legend:
Customize the legend background, border, and font style.
chart.LegendTextPaint = new LiveChartsCore.SkiaSharpView.Painting.SKPaint
{
Color = SkiaSharp.SKColors.Blue,
Typeface = SkiaSharp.SKTypeface.Default,
TextSize = 18
};
Enabling/Disabling Animation and Its Performance Impact
Animations in LiveCharts make transitions smoother, but they can be turned off for better performance.
Enable/Disable Animations:
lineSeries.AnimationsSpeed = TimeSpan.FromMilliseconds(0); // Disable animation
Performance Impact of Animations:
Interaction Options
LiveCharts supports various interactive features, making charts more useful.
Zoom and Pan:
LiveCharts supports interactivity features such as zooming and panning out of the box.
chart.ZoomMode = LiveChartsCore.Measure.ZoomAndPanMode.Both; // Enable both axes zooming
or
lineChart.ZoomMode = LiveChartsCore.Measure.ZoomAndPanMode.X; // Enable zoom and pan for the X-axis
Turning Series On/Off:
Use a CheckBox to toggle the visibility of a series.
lineSeries.IsVisible = false; // Hide the series
Displaying Values on Hover:
chart.TooltipPosition = LiveChartsCore.Measure.TooltipPosition.Top;
chart.TooltipTextPaint = new LiveChartsCore.SkiaSharpView.Painting.SKPaint
{
Color = SkiaSharp.SKColors.Black,
TextSize = 14
};
Handling Click Events:
You can subscribe to events for interacting with points.
领英推荐
lineSeries.PointMeasured += (sender, e) =>
{
var value = e.Point.PrimaryValue;
MessageBox.Show($"Point value: {value}");
};
Customizing the Chart Appearance
LiveCharts provides many options for customizing the appearance of charts.
Changing Colors and Styles:
lineSeries.Stroke = new SkiaSharp.SKColor(255, 0, 0); // Set line color to red
lineSeries.GeometrySize = 10; // Set point size
lineSeries.Fill = new SkiaSharp.SKColor(255, 0, 0, 128); // Set fill with transparency
Customizing Axes:
lineChart.XAxes = new Axis[]
{
new Axis { LabelsRotation = 45, Name = "Months" }
};
lineChart.YAxes = new Axis[]
{
new Axis { Name = "Value", Labeler = value => value.ToString("N2") }
};
Starting Axes from a Non-Zero Value:
chart.YAxes = new Axis[]
{
new Axis { MinLimit = 10 } // Start Y-axis from 10
};
Using Time as Horizontal Axis:
chart.XAxes = new Axis[]
{
new Axis
{
Labeler = value => DateTime.FromOADate(value).ToString("MMM dd"),
LabelsRotation = 45
}
};
Styling Axes:
chart.XAxes[0].TextPaint = new LiveChartsCore.SkiaSharpView.Painting.SKPaint
{
Color = SkiaSharp.SKColors.Green,
TextSize = 12
};
Setting Axis Intervals:
Control the distance between axis ticks.
chart.XAxes[0].UnitWidth = 2;
Handling Events (Click, Hover, etc.)
You can also respond to user interactions like clicking or hovering over the data points.
lineSeries.PointMeasured += (sender, e) =>
{
MessageBox.Show($"Clicked value: {e.Point.PrimaryValue}");
};
Real-Time Data Updates
LiveCharts is designed with real-time updates in mind, allowing you to change data dynamically.
var lineSeries = new LineSeries<double>
{
Values = new ObservableCollection<double> { 3, 5, 7, 9 }
};
lineChart.Series = new ISeries[] { lineSeries };
// Update values dynamically
lineSeries.Values.Add(6);
lineSeries.Values[0] = 4;
Live Data and Streaming Charts
LiveCharts is capable of real-time updates, making it suitable for displaying live data.
Using ObservableCollection for Real-Time Data Updates:
var liveData = new ObservableCollection<double> { 1, 2, 3, 4, 5 };
lineSeries.Values = liveData;
// Add new data points dynamically
Task.Run(() =>
{
while (true)
{
Invoke(new Action(() =>
{
liveData.Add(new Random().NextDouble() * 10);
if (liveData.Count > 50) liveData.RemoveAt(0); // Keep only the latest 50 points
}));
Thread.Sleep(500); // Update every 500 ms
}
});
Auto-Scrolling Chart:
Automatically scroll the chart to display the latest data.
chart.XAxes[0].MaxLimit = liveData.Count - 1;
Smoothing Live Data:
Apply filters like moving average to smooth out noise in the live data.
Handling a High Number of Points
To maintain performance with large datasets, you can use the following strategies:
Data Sampling:
Reduce the number of points by sampling data.
var sampledData = originalData.Where((x, index) => index % 10 == 0).ToArray();
Direct Rendering Mode:
Switch to a mode optimized for large datasets.
lineSeries.LineSmoothness = 0; // Disable line smoothing for better performance
Lazy Data Loading:
Load data in chunks to avoid freezing the UI.
// Example of asynchronous data loading
Task.Run(() =>
{
foreach (var chunk in dataChunks)
{
Invoke(new Action(() => lineSeries.Values.AddRange(chunk)));
}
});
Enable Hardware Acceleration:
Leverage GPU rendering if supported.
Additional Tips
This overview should help get you started with LiveCharts for WinForms development. The library's documentation and community can further assist you with more advanced configurations and features.
Conclusion
LiveCharts is a flexible, modern, and easy-to-use charting library for .Net applications. It provides the tools you need to create various types of charts with interactivity and real-time data updates. It is not really good with huge numbers of points (I tested it with 360000 point and the result was inacceptable. Even with 36000 point it was very slow) but great for normal charts with low and medium numbers of points. This article covers the basics, but you can explore many more features like customizing tooltips, legend settings, animations, and more.
#plotting #livechart #chart #csharp #dotnet