Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

MSChart Extension - Zoom and Pan Control

Rate me:
Please Sign up or sign in to vote.
4.93/5 (26 votes)
19 Jul 2012MIT5 min read 171K   13.7K   59   61
Implement Zoom and Pan Controls for MSChart
In this article, you will learn about an extension class named "MSChart Extension" that is created to extend functionality of MSChart control in Visual Studio for WinForms applications.

Also available in NuGet and GitHub.

Update

MSChart Extension had been updated to Version 2.2.0. New features are described in the following articles:

Introduction

This article describes an extension class named "MSChart Extension" which is created to extend functionality of Microsoft Chart (MSChart) control in Visual Studio for WinForms applications.

Background

Microsoft Chart (MSChart) in Visual Studio is a great Windows Forms (WinForms) control to create chart for a standalone application. However, there are several features that could be added and improved to make this control more user friendly.

Zooming and panning are two common features for chart when dealing with large amount of data. Unfortunately, there is no easy way to have these two features enabled with MSChart. Although there is a built in Zoom control, it is not very user friendly which is described below. On the other hand, panning is not available. I searched around the web but didn't find any reliable solutions.

I tried to implement these two features in MSChart by writing custom codes and YES, it is possible. Instead of copying and pasting the same piece of code over and over again to every single project that I need, I created this MSChart Extension class which put all these additional features in a separated assembly which can be simply added as reference when needed.

Features List

  • Fast Clear Data
  • Windowed Zoom in and Zoom Out
  • Pan
  • Show / hide series

Fast Clear Data

MSChart has a known problem which impacts most of the users which is the speed of clearing data points. This become worst when dealing with large amount of data. Workaround for this solution had been published by Microsoft and users around the web to fix this problem. (original link)

An extension method of this function is implemented in MSChart extension as below:

C#
internal static class MSChartExtension
{
    public static void ClearPoints(this Series sender)
    {
        sender.Points.SuspendUpdates();
        while (sender.Points.Count > 0)
            sender.Points.RemoveAt(sender.Points.Count - 1);
        sender.Points.ResumeUpdates();
        sender.Points.Clear(); //NOTE 1
    }
}

Note 1: I added one additional line Points.Clear() at the end of the function to ensure the chart axis updated correctly on next plot. Without adding this line, I observed that previous axis settings will be used when plotting new data points right after calling ClearPoints().

To use this feature, one just needs to call ClearPoints() from chart series.

C#
//Clear Data Points (Extension)
myChart.Series[0].ClearPoints();

Windowed Zoom

This is an improvement version of zoom control with zoom out (full view) instead of using built in zoom control in MSChart. The main reason for recreating this feature is because zooming out is really a pain where you need to zoom out each axis separately by clicking a button on the axis by number of times that I zoomed in. Moreover, the built in controls do not seems to works well with annotations.

Notes: Zoom out function is available in pop up menu when chart is zoomed.

Pan

Panning allowed user to move zoomed window using mouse. This is much better than moving the horizontal and vertical scroll bar.

Show / Hide Series

Sometimes, it is necessary to plot chart with multiple series for data comparison. However, it would not be easy to visualize the data for each individual series when we have multiple series overlapping each other. Show and hide series function provides a flexibility to hide each series as you wish. MSChart extension will automatically detect number of series used in chart, no setup is required to use this feature. Each series can be hide / show from context menu.

Annotations (Version 1.2.0)

Extensions methods to create chart annotations are added in Version 1.2.0 as below:

  • DrawHorizontalLine
  • DrawVerticalLine
  • DrawLine
  • DrawRectangle
  • DrawText

The standard way to add an annotation to MSChart in run-time is create an annotation object and add it to the annotation list of the chart. Adding one annotation normally involves several lines of codes as we need to overwrite some of those default properties in order to show the annotation correctly in the chart.

With the extension methods provided above, adding annotation can be easily done in a single function call. Colors, line weight, line style and position are exposed as input parameters.
Functions listed above are just few of the commonly used annotation type. You may create a similar function for other types of annotation using the similar methods.

NOTE: Please note that these functions are created to add annotation to first chart area with primary axis.

Codes below show an example of adding horizontal line to chart. ClipToChartArea, AxisXName, YAxisName, and IsInfinite are properties that we need to overwrite its default values. AxisXName and YAxisName are hidden properties which is not visible in IntelliSense.

Custom annotation name should only be assigned after annotation was added to annotation list. This is because the Name property will be overwrite with auto generated value when adding the object to annotation list.

C#
 public static void DrawHorizontalLine(this Chart sender, double y,
    Drawing.Color lineColor, string name = "",
    int lineWidth = 1, ChartDashStyle lineStyle = ChartDashStyle.Solid)
{
    HorizontalLineAnnotation horzLine = new HorizontalLineAnnotation();
    string chartAreaName = sender.ChartAreas[0].Name;
    horzLine.ClipToChartArea = chartAreaName;
    horzLine.AxisXName = chartAreaName + "\\rX";
    horzLine.YAxisName = chartAreaName + "\\rY";
    horzLine.IsInfinitive = true;
    horzLine.IsSizeAlwaysRelative = false;

    horzLine.Y = y;
    horzLine.LineColor = lineColor;
    horzLine.LineWidth = lineWidth;
    horzLine.LineDashStyle = lineStyle;
    sender.Annotations.Add(horzLine);

    if (!string.IsNullOrEmpty(name)) horzLine.Name = name;
}

Using the Code

To use this extension package, simply add MSChart assembly to reference of the project. Additional features and dedicated context menu can be enabled by the following function call.

C#
private void AttachChartControl()
{
    //Enable Extension Functions and Context Menu
    myChart.EnableZoomAndPanControls(ChartCursorSelected, ChartCursorMoved);
}

private void ChartCursorSelected(double x, double y)
{
    txtChartSelect.Text = x.ToString("F4") + ", " + y.ToString("F4");
}
private void ChartCursorMoved(double x, double y)
{
    txtChartValue.Text = x.ToString("F4") + ", " + y.ToString("F4");
}

ChartCursorSelected and ChartCursorMoved are two optional callbacks to notify parent when chart coordinate changed. ChartCursorSelected will be called when a point in chart area is selected whereas ChartCursorMoved will trigger when mouse is move in chart area. x and y values in these two callbacks are values for X-Axis and Y-Axis. It is hard coded to use primary axis at this moment.

This operation is reversible by calling the following function:

C#
//Disable Extension Functions and restore chart settings
myChart.DisableZoomAndPanControls();

MSChart Extension comes with a built in pop up menu which allows user to use features such as zoom and pan controls during run-time. All functions such as zoom, pan, select and series hide / show can be accessed from context menu. This context menu is shown when right click mouse in chart with Zoom and Pan controls enabled as shown above.

Future Improvement

  • Add option to select between primary / secondary axis for Select tool and callback functions.
  • Append MSChart Extension's context menu to user defined context menu if exists.
  • Implement 2 cursor to calculate different between 2 points.

History

  • 3rd April, 2012: Initial release (Version 1.0.0)
  • 4th April, 2012: (Update) Added callback function's description and Future improvement list
  • 18th July, 2012: (Update) Added Annotation Functions (Version 1.2.0)
  • 19th July, 2012: Fixed download package

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Technical Lead
Malaysia Malaysia
Official Page: www.codearteng.com

Comments and Discussions

 
Questionto get the parameters out Pin
Member 767459528-Jun-15 18:56
Member 767459528-Jun-15 18:56 
AnswerRe: to get the parameters out Pin
Code Artist4-Jul-15 3:13
professionalCode Artist4-Jul-15 3:13 
QuestionArgumentException Pin
Member 1111716920-Nov-14 2:49
Member 1111716920-Nov-14 2:49 
QuestionSeries enabled/disabled event Pin
shehrozeee5-Sep-14 8:00
shehrozeee5-Sep-14 8:00 
AnswerRe: Series enabled/disabled event Pin
Code Artist7-Sep-14 2:15
professionalCode Artist7-Sep-14 2:15 
GeneralRe: Series enabled/disabled event Pin
shehrozeee7-Sep-14 2:30
shehrozeee7-Sep-14 2:30 
GeneralRe: Series enabled/disabled event Pin
Code Artist9-Sep-14 3:45
professionalCode Artist9-Sep-14 3:45 
QuestionQuestion: Zooming AND panning with second Y-axis possible? Pin
Member 1098919423-Aug-14 2:50
Member 1098919423-Aug-14 2:50 
AnswerRe: Question: Zooming AND panning with second Y-axis possible? Pin
Member 1098919423-Aug-14 15:31
Member 1098919423-Aug-14 15:31 
GeneralRe: Question: Zooming AND panning with second Y-axis possible? Pin
Code Artist29-Aug-14 4:30
professionalCode Artist29-Aug-14 4:30 
GeneralRe: Question: Zooming AND panning with second Y-axis possible? Pin
Code Artist30-Aug-14 3:14
professionalCode Artist30-Aug-14 3:14 
GeneralRe: Question: Zooming AND panning with second Y-axis possible? Pin
Member 109891945-Sep-14 16:12
Member 109891945-Sep-14 16:12 
QuestionChoose Select, Zoom, Pan and Zoom Out tools from a button Pin
Member 1097611728-Jul-14 3:51
Member 1097611728-Jul-14 3:51 
AnswerRe: Choose Select, Zoom, Pan and Zoom Out tools from a button Pin
Code Artist21-Aug-14 3:06
professionalCode Artist21-Aug-14 3:06 
QuestionHow can you show dates/times at the x Axis? Pin
pavfrang20-Jul-14 6:29
pavfrang20-Jul-14 6:29 
QuestionVBA Pin
Doug Kelly15-Oct-13 7:27
Doug Kelly15-Oct-13 7:27 
AnswerRe: VBA Pin
Code Artist15-Oct-13 12:51
professionalCode Artist15-Oct-13 12:51 
NewsUpdated version with new features available on NuGet and github Pin
Pat Kujawa30-Jul-13 10:28
Pat Kujawa30-Jul-13 10:28 
QuestionCursors Pin
Member 99641233-Apr-13 21:38
Member 99641233-Apr-13 21:38 
AnswerRe: Cursors Pin
Code Artist4-Apr-13 1:41
professionalCode Artist4-Apr-13 1:41 
GeneralRe: Cursors Pin
Member 99641234-Apr-13 2:08
Member 99641234-Apr-13 2:08 
GeneralRe: Cursors Pin
Code Artist4-Apr-13 2:18
professionalCode Artist4-Apr-13 2:18 
GeneralRe: Cursors Pin
Member 99641234-Apr-13 2:29
Member 99641234-Apr-13 2:29 
GeneralThanks Pin
Member 994197626-Mar-13 1:41
Member 994197626-Mar-13 1:41 
GeneralRe: Thanks Pin
Code Artist26-Mar-13 3:19
professionalCode Artist26-Mar-13 3:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.