Tuesday, July 16, 2013

Surface Map in C# winforms using ChartDirector

The following code shows how to plot a surface map (similar to the one in MATLab) in C# winform using ChartDirector (The data to be displayed is stored in a matrix):

private void UpdatePrimitiveFitnessSurfaceMapByData(WinChartViewer viewer, List<double[]> matrix)
        {
            int dim1 = matrix.Count;
            if (dim1 == 0) return;
            int dim2 = matrix[0].Length;

            // The x and y coordinates of the grid
            double[] dataX = new double[dim1];
            double[] dataY = new double[dim2];

            for (int i = 0; i < dim1; ++i)
            {
                dataX[i] = i;
            }
            for (int i = 0; i < dim2; ++i)
            {
                dataY[i] = i;
            }

            double[] dataZ = new double[(dataX.Length) * (dataY.Length)];
            for (int i = 0; i < dim1; ++i)
            {
                for (int j = 0; j < dim2; ++j)
                {
                    dataZ[i * dim2 + j] = matrix[i][j];
                }
            }

            // Create a SurfaceChart object of size 720 x 600 pixels
            SurfaceChart c = new SurfaceChart(720, 600);

            // Add a title to the chart using 20 points Times New Roman Italic font
            c.addTitle("Variable Fitness Distribution", "Times New Roman Italic", 20);

            // Set the center of the plot region at (350, 280), and set width x depth
            // x height to 360 x 360 x 270 pixels
            c.setPlotRegion(350, 280, 360, 360, 270);

            // Set the data to use to plot the chart
            c.setData(dataX, dataY, dataZ);

            // Spline interpolate data to a 80 x 80 grid for a smooth surface
            c.setInterpolation(80, 80);

            // Add a color axis (the legend) in which the left center is anchored at
            // (645, 270). Set the length to 200 pixels and the labels on the right
            // side.
            c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);

            // Set the x, y and z axis titles using 10 points Arial Bold font
            c.xAxis().setTitle("Generation", "Arial Bold", 10);
            c.yAxis().setTitle("Terminal Variable Index", "Arial Bold", 10);
            c.zAxis().setTitle("Variable Fitness Distribution",
                "Arial Bold", 10);

            // Output the chart
            viewer.Chart = c;
        }

No comments:

Post a Comment