Line Chart With Multiple Axes in WPF

A common scenario when building charts is the ability to render multiple series bound to multiple axes, each one with its own scale. To deal with this issue, MindFusion.Charting for WPF control has added support for multiple axes of all types – X, Y, Y2, X2 and in this post we’ll look how to add and customize them and how to create series bound to a given axis.

The sample imitates a production chart, where three different scales measure three different values – work output, capital and energy consumption – all of which presumably participate in producing a single unit of a product. On the right side we have a single Y2 axis, which measures the amount of units produced. The X-axis displays the time scale. Let’s look at the chart elements, one by one.

I. The Y-Axes

The Y-axes, as all axes in the chart are an instance of the Axis class and are added to the appropriate collection property. The Axis class defines all types of useful properties needed to customize an axis. We define the three axes in XAML:

<chart:linechart.yaxes>
    <chart:axescollection>
        <chart:axis minvalue="0" interval="5" maxvalue="60" labelformat="F0" tick="3" title="kWh/day" titlerotationangle="270" labelstroke="Red" titlestroke="Red"></chart:axis>
        <chart:axis minvalue="0" interval="300" maxvalue="2100" title="Capital (USD)" tick="3" titlerotationangle="270" labelstroke="Purple" titlestroke="Purple"></chart:axis>
        <chart:axis minvalue="100" interval="2.5" maxvalue="130" title="Work Productivity (%)" customlabelposition="AutoScalePoints" axiscrossingpoint="100.0" labeltype="CustomText" tick="3" titlerotationangle="270" labelstroke="Green" titlestroke="Green"></chart:axis>
    </chart:axescollection>
</chart:linechart.yaxes>

The property names easily describe what is set: the minimum and maximum values on each of the three axes, the title, the stroke for the labels and the title, the interval and the length of the axis ticks. Let’s note that the type of labels for the last Y-axis is “CustomText” – this means we will specify the labels explicitly rather than allow the control to generate them as with the other two axes – they don’t set a label type and the default value (the auto scale) is rendered.

Here is how we define the labels:

double start = 100.0;

    //130 is the last number at the axis
    while (start <= 130)
    {
        string l = start.ToString("F1") + "%";
        chart.YAxes[2].Labels.Add(l);
        start += 2.5;
    }

II. The Y2 Axis

The Y2-axis is just one and it is entirely declared in XAML:

<chart:linechart.y2axes>
    <chart:axescollection>
        <chart:axis minvalue="0" interval="1000" maxvalue="12000" tick="3" labelformat="F0" titlerotationangle="270" title="Units"></chart:axis>
     </chart:axescollection>
</chart:linechart.y2axes>

The label format is set with the standard .NET numeric strings – in this case it is a floating number without trailing zeros. In this axis, as well in the other Y-axes you might have noticed that we use the TitleRotationAngle property. This property rotates the title label at an arbitrary angle between 0 and 360. In our case we want the label drawn vertically, to conserve space.

III. The Series

The series are created in code. They specify scatter type because we want each series to have markers at data points. The YAxis property specifies the Y-axis, which a given Series is bound to. Finally, we specify the tool tip type because we want to have a tool tip when the mouse hovers a data point.

 LineSeries series0 = new LineSeries();
 series0.YAxis = chart.YAxes[0];
 series0.ScatterType = ScatterType.Square;
 series0.ScatterFills = new BrushCollection() { Brushes.Pink };
 series0.ScatterStrokes = new BrushCollection() { Brushes.Red };
 series0.Strokes = new BrushCollection() { Brushes.Red };
 series0.ToolTipType = ToolTipType.ChartData;

The data is random generated numbers. We use the Axis.XData and Axis.YData properties to set it.

 for (int i = 0; i < 30; i++)
     {
        series0.XData.Add(i * 6);
        data1.Add(rand.NextDouble() * 60.0);     
      }

      data1.Sort();
      series0.YData = new DoubleCollection(data1);
      //don't forget to add the series
      chart.Series.Add(series0);

Last but not least – don’t forget to add the series to the Series collection property of the chart. With that our chart is ready – here is the result:

Charting for WPF: Multiple Axes and Series

Charting for WPF: Multiple Axes and Series

You can download the sample with the chart libraries from here:

WPF Chart With Multiple Axes Sample Download

If you have any questions regarding the chart component use the forum, email or the help desk to contact MindFusion. More information about Charting for WPF, which includes a premium 3D charting library and a Real time charting library optimized to handle huge data sets can be found here.

Scheduling for WPF, V 3.4 and Reporting for WPF, V1.4

We are pleased to announce new versions for two of MindFusion’s WPF components – Reporting and Scheduling. Below we list the new features and improvements in each of the controls.

WebForms Scheduler by MindFusionNew in Scheduling for WPF, V3.4

Interactive Recurrence Rescheduling
Recurrences can be rescheduled interactively by holding down the RescheduleRecurrenceKey while dragging a recurrent item. The control tries to preserve the current pattern of the recurrence when possible. Otherwise, you can modify the recurrence to accommodate to the new start and end times of the modified item. Interactive rescheduling is not registered in the undo history.

New Theme
A new built-in theme is available in the Scheduler control – the Light theme. It is available through the ThemeType enumeration.

Scheduler for WPF: The Light Theme

Scheduler for WPF: The Light Theme

New API Members
Several new properties and events have been added to the control:

You can download the trial version of the control directly from this link:

Scheduling for WPF, V3.4 Trial Version Download

The component is also available on Nuget. To install the component, run the following command in the Package Manager Console:

PM> Install-Package MindFusion.Scheduling.Wpf

WPF Reporting ToolNew in Reporting for WPF, V1.4

Report Parameters
Parameters can now be added to a report through the new Parameters collection of the Report class. The parameters provide name, description and value and can be of any type, including expression. For more information about parameters, check the Report Parameters topic.

Barcodes
MindFusion WPF Reporter can now display UPC-A, UPC-E, EAN-8, EAN-13, and QR barcodes. The barcodes are represented by the new Barcode report item.

WPF Reporter: Barcode Report Items

WPF Reporter: Barcode Report Items

Improved charts
Several new properties have been added to the LineChart class to imporive the customization for the plot, grid, legend and axes. The axes settings can be specified through the new XAxisSettings and YAxisSettings properties. The AxesChart class exposes four new properties, which can be used to specify the intervals displayed by the chart axes. The new properties are XMinValue, XMaxValue, YMinValue, and YMaxValue.

Miscellaneous

  • Report items can be searched by name through the new FindItem method.
  • Fixed an issue with horizontal data ranges.
  • Items in data range headers and footers can now bind to the data source of the data range.
  • New sample illustrating the Barcode report items.

You can download the trial version of the control directly from this link:

Reportingfor WPF, V1.4 Trial Version Download

The component is also available on Nuget. To install the component, run the following command in the Package Manager Console:

PM> Install-Package MindFusion.Reporting.Wpf

Technical support: You can write at the Scheduling for WPF discussion board and Reporting for WPF discussion board. Additionally, you can write us at support@mindfusion.eu. Anyway we’ll be glad to answer your questions, comments and recommendations and assist you on how to use the MindFusion WPF controls.

About Scheduling for WPF: The perfect programming tool to enhance your WPF application with a compelling set of ready-to-use calendar features. Choose among six types of schedule views all optimized for high performance and easy customization. Treat your users to the convenience of creating appointments with reminders and recurrence options on the fly with the built-in forms. Change every single calendar element to achieve the perfect look without compromise – apply styling, customize the fonts and colors or simply set one of the elegant predefined themes. Persisting the calendar into a variety of formats is easily done with the integrated exporters and importers. The control is also packed with a rich event set that gives you full control over the user’s actions. More about Scheduler for WPF here.

About Reporting for WPF: A programming tool that provides developers with everything they’ll need to create high-impact data driven reports using WPF. The control supports comprehensive list of report elements, which can be nested, combined and customized to create reports optimized for the needs of your current WPF application. A full-featured chart component is integrated into the report tool and you can extend every single report with a compelling chart of your choice. The report can be saved into a variety of formats and rendered on the screen with the built-in elegant viewer for optimal performance. Further details about MindFusion WPF Reporter here.

MindFusion.Gauges: Creating a Stopwatch

This blog will demonstrate how to create a simple stopwatch based on the OvalGauge component (part of MindFusion.Charting for WinForms and MindFusion.Pack for WinForms).

Introduction
We start off by creating a new Windows Forms Application in Visual Studio and adding an OvalGauge control to the main form. Set the gauge’s Dock property to Fill and its Name to “stopwatch”.

Setting up the scales
The stopwatch will contain two scales – a bigger one, which should display the seconds, and a smaller one – for the minutes. The minute scale will be positioned in the upper half of the gauge area. The scales can be created and configured in design-time – through the property grid – or in code. In the Property grid navigate to the Scales property of the OvalGauge control and click the ‘…’ button or hit F4 to open the OvalScale Collection Editor. In this editor, add two scales by pressing the ‘Add’ button. Edit the following properties of the second scale:

Name = "SecondsScale"
StartAngle = -90
EndAngle = 270
StartWidth = 0
EndWidth = 0
Stroke = Color=Black, Width=0

MinorTickSettings.ShowTicks = True
MinorTickSettings.Count = 4
MinorTickSettings.Stroke = Color=(85, 85, 85), Width=0
MinorTickSettings.TickShape = Line
MinorTickSettings.TickWidth = 5%
MinorTickSettings.TickAlignment = OuterInside

MiddleTickSettings.ShowLabels = False
MiddleTickSettings.Count = 5
MiddleTickSettings.Stroke = Color=(0, 0, 0), Width=0
MiddleTickSettings.TickShape = Line
MiddleTickSettings.TickWidth = 8%
MiddleTickSettings.TickAlignment = OuterInside

MajorTickSettings.Count = 12
MajorTickSettings.FontFamily = "Calibri"
MajorTickSettings.FontSize = 20%
MajorTickSettings.FontStyle = Regular
MajorTickSettings.LabelOffset = 9%
MajorTickSettings.LabelRotation = None
MajorTickSettings.ShowMaxValueTick = Never
MajorTickSettings.Stroke = Color=(0, 0, 0), Width=2
MajorTickSettings.TickShape = Line
MajorTickSettings.TickWidth = 12%
MajorTickSettings.TickAlignment = OuterInside

In addition, add four custom intervals to the MajorTickSettings.CustomIntervals collection, representing the intervals [0-0], [15-15], [30-30], and [45-45] respectively. Set the Fill property of each custom interval to (187, 31, 33). These objects indicate that the labels inside the corresponding intervals will be colored in red.

For simplicity, the properties of the minute scale are omitted. They are similar to those of the second scale, the main difference being that the minute scale is positioned and sized through the ScaleRelativeCenter and ScaleRelativeRadius properties.

Adding pointers

In the OvalScale Collection Editor dialog add a pointer to each of the two scales. To do this, select the scale, navigate to the Pointers property in the grid and press the ‘…’ button or F4. This will open the Pointer Collection Editor dialog. Name the pointer of the minute scale “MinutesPointer” and the one in the second scale – “SecondsPointer”. We will use these names later in code to identify and search for the pointers. Set the width of the two pointers to 30% and 20% respectively. Then close all editors. We will custom draw the pointers so there is no need to specify any more properties.

To draw the pointers, handle the PrepaintPointer event of the OvalGauge class. This event is raised for each pointer in the gauge individually before the pointer is painted by the control. The event can be used to cancel the default pointer drawing by setting the CancelDefaultPainting to true. A simplified version of the event handler that paints the two pointers is listed below.

private void stopwatch_PrepaintPointer(object sender, PrepaintEventArgs e)
{
    e.CancelDefaultPainting = true;

    Brush fill = new SolidBrush(Color.FromArgb(175, 8, 9));

    GraphicsState state = e.Graphics.Save();
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.ScaleTransform(e.Element.RenderSize.Width, e.Element.RenderSize.Height);

    if (e.Element.Name == "SecondsPointer")
    {
         var polygon = new PointF[]
         {
             new PointF(0.1f, 0.35f),
             new PointF(1, 0.45f),
             new PointF(1, 0.55f),
             new PointF(0.1f, 0.65f)
         };
         var ellipse1 = new RectangleF(0, 0, 0.2f, 1f);

        // Draw the pointer itself
        e.Graphics.FillPolygon(fill, polygon);
        e.Graphics.FillEllipse(fill, ellipse1);
    }
    else if (e.Element.Name == "MinutesPointer")
    {
        var polygon = new PointF[]
        {
            new PointF(0.15f, 0.35f),
            new PointF(1, 0.45f),
            new PointF(1, 0.55f),
            new PointF(0.15f, 0.65f)
        };
        var ellipse1 = new RectangleF(0, 0, 0.3f, 1f);

        e.Graphics.FillPolygon(fill, polygon);
        e.Graphics.FillEllipse(fill, ellipse1);
    }

    e.Graphics.Restore(state);
    fill.Dispose();
}

Activating the stopwatch

Now we need means to start, stop, and reset the stopwatch. First, declare two member variables in the form – startTime and elapsedTime, of type DateTime and TimeSpan respectively. The first variable will store the time when the stopwatch was most recently started. The second variable will store the total elapsed time.

Go to the Visual Studio designer, select the form, navigate to the Padding property and change its value to “0, 0, 0, 50”. The gauge will shrink, leaving some space at the bottom. Add two buttons to the form, below the gauge, and set their texts to “Start” and “Reset” respectively. In addition to the buttons, add a Timer component to the form. When the stopwatch is started, we will use this timer to update the pointers. Handle the Click events of the two buttons. The first button will start/stop the stopwatch. The second button will reset the stopwatch. Here is the event handlers of the two buttons:

private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
    {
        UpdateTime();
        UpdatePointers();

        timer1.Stop();
        button1.Text = "Start";
    }
    else
    {
        button1.Text = "Stop";
        startTime = DateTime.Now;
        timer1.Start();
    }
}

private void button3_Click(object sender, EventArgs e)
{
   elapsedTime = TimeSpan.Zero;
   UpdatePointers();
}

Depending on the current state of the application, the first button will either start or stop the timer. The second button will set the elapsed time to 0:00, effectively resetting the stopwatch. Both buttons rely on the method UpdatePointers, which adjusts the gauge pointers according to the currently elapsed time. This method uses the GetElementByName method of the gauge to access the pointers by name and update their values:

private void UpdatePointers()
{
    var minutesPointer = (Pointer)stopwatch.GetElementByName("MinutesPointer");
    var secondsPointer = (Pointer)stopwatch.GetElementByName("SecondsPointer");
    minutesPointer.Value = (float)elapsedTime.TotalMinutes;
    secondsPointer.Value = (float)Math.Round((float)(elapsedTime.TotalSeconds % 60), 1);
}

Finally, handle the Tick event of the timer.

private void timer1_Tick(object sender, EventArgs e)
{
    UpdateTime();
    UpdatePointers();
}

The image below illustrates the running stopwatch:

gauge-stopwatch

The source code of the sample is available for download from here:
https://mindfusion.eu/_samples/GaugesStopwatch.zip

The MindFusion.Charting for WinForms component can be downloaded from here:
https://www.mindfusion.eu/ChartWinFormsTrial.zip

About MindFusion.Charting for WinForms: A professional programming component for WinForms, which lets you create remarkable charts and gauges fast and easy. The tool supports all major chart types – line, pie, radar and bar – and numerous variations of them – column, area, bubble, polar, doughnut etc, as well as oval and linear gauges.

MindFusion Pack for ASP.NET 2014.R1

We have just released MindFusion.WebForms Pack 2014.R1. The diagramming component in the pack offers several new features – here is an overview:

diagram16x16Diagramming for ASP.NET

Import of Visio 2013 files
The new Visio2013Importer class can import *.vsdx files, created by Visio 2013. It is part of the MindFusion.Diagramming.Import.Visio.dll assembly and you must reference it if you want to use the importer. The Import method has various overloads, which let you choose how the Visio diagram is imported – as a whole diagram whose content is merged from all imported pages or as a DiagramDocument, whose pages correspond to the Visio drawing pages. Each Visio connector and node shape in the original diagram is represented by a matching DiagramLink and DiagramNode object in the resulting flowchart.

Canvas mode improvements

  • The HandlesStyle property of nodes is now supported in Canvas mode.
  • Dynamic links are now supported in Canvas mode.
  • You can apply layout algorithms to the content of a ContainerNode by calling its arrange method.
  • and more.

Java mode improvements

  • RoundedLinks and RoundedLinksRadius properties are now supported in Java mode.
  • AutoSnapLinks is now honored in Java mode; links drawn interactively snap to a nearby node from a distance.
  • createFontEx method added to ScriptHelper creates bold, italic and underlined fonts.
  • as well other improvements.

Miscellaneous

Several new predefined shapes are available in the Shapes class – RightTriangle, Decagon, Trapezoid, Star4Pointed, Star5Pointed, Star6Pointed, Star7Pointed, Star16Pointed, Star24Pointed, Star32Pointed, Donut and Plaque.

The new predefined node shapes.

The new predefined node shapes.

The trial version is available for download from this link:

Download MindFusion Pack for WebForms, 2014.R1

About MindFusion.WebForms Pack: A set of WebForms components that add great variety of features to your ASP.NET application with a few mouse clicks. The pack contains advanced components for diagramming, scheduling, charting and UI (Accordion, ColorPicker, TabControl, Window, WindowHost, DockControl, Button, Slideshow, Zoom and more). Each tool boasts easy to learn and use API and is quickly integrated into any web application that targets the ASP.NET platform. The controls support numerous options for styling, data import / export, user interaction and offer rich event set. There are plenty of samples and step-by-step tutorials as well detailed documentation.

Use the features page for each of the tools to find out more about its capabilities and
the numerous ways it can boost your performance and speed up the development of your application:

Visit the buy page for details on the licensing scheme and prices. If you have questions please contact us. We shall be happy to assist you.

MindFusion Pack for ASP.NET, V2013.R2

MindFusion has released Pack for ASP.NET, V2013.R2. Here is an overview of the most important new features in the components within the pack:

diagram16x16 MindFusion.Diagramming for WebForms

Import of OpenOffice Draw files

The new DrawImporter class lets you import *.odg files created by the OpenOffice Draw Vector graphics editor. You just need to add a reference to the MindFusion.Diagramming.Import.Draw.dll assembly and are ready to use it. You can use various overloads of the Import method to import the OpenOffice drawing into a DiagramDocument whose pages correspond to the Draw pages, or into a single Diagram whose content is merged from all imported pages.

Import any type of diagram from

Import any type of diagram from an *.odg file

Canvas Mode Improvements

ContainerNode Improvements

  • Child nodes are now drawn by their containers; when containers overlap, the children of a lower container cannot appear in front of the upper container anymore
  • The ClipChildren property specifies whether to clip child items to container’s boundaries
  • The ZIndex property no longer changes automatically when dropping nodes into a container
  • and others

Miscellaneous

  • The MeasureUnit property now supports Centimeter and WpfPoint values. The latter allows loading diagram files saved by WPF and Silverlight versions of the control with their default units.
  • SwimlaneLayout now honors the Anchoring.Keep property value.
  • New line and quote characters in Tag strings are now escaped when passed to client-side click events in ImageMap mode, avoiding script errors.
  • As well a few bug fixes and API changes

chartMindFusion.Charting for WebForms

Themes

Chart themes are now XML files that you can save and load with the SaveTheme and LoadTheme methods. You can use the theme editor tool provided with the control to edit, save and load themes in a fast and intuitive way. The control provides an initial set of 8 predefined themes.

Major/Minor Axis Ticks

Use the new MajorTickLength and MinorTickLength properties to divide a chart axis in a more precise and accurate manner. The number and pen for the ticks are set with MinorTicksPerInterval, MajorTickPen and MinorTickPen.

Major and minor axis ticks

Major and minor axis ticks

ToolTips

You can apply tooltips on all chart types. Area charts in particular can show a different tooltip for every region between two adjacent data points.

Interactive Editing of Data

Line and bar chart elements can be dragged with the mouse. Bars can be dragged either in horizontal or vertical direction according to their orientation. Line chart points can be dragged in any direction. The dragging behavior is set with the Behavior property.

As well other useful new features.

You can read more about the new features of the components in the ASP.NET Pack at the forum. The new version is available for download from this link:

Download MindFusion Pack for WebForms, VR2.2013

About MindFusion.WinForms Pack: A set of WebForms components that add great variety of features to your ASP.NET application with a few mouse clicks. The pack contains advanced components for diagramming, scheduling, charting and UI (Accordion, ColorPicker, TabControl, Window, WindowHost, DockControl, Button, Slideshow, Zoom and more). Each tool boasts easy to learn and use API and is quickly integrated into any web application that targets the ASP.NET platform. The controls support numerous options for styling, data import / export, user interaction and offer rich event set. There are plenty of samples and step-by-step tutorials as well detailed documentation.

Use the features page for each of the tools to find out more about its capabilities and
the numerous ways it can boost your performance and speed up the development of your application:

Visit the buy page for details on the licensing scheme and prices. If you have questions please contact us. We shall be happy to assist you.