Use ZedGraph to generate an image from a console application

From ZedGraphWiki

Jump to: navigation, search

In some cases, you don't want all the gui interface or interactivity, you just want to generate a graph as a bitmap or other Image type, and output the result as a file stream. You can do this with ZedGraph -- the only requirement is access to the GDI+ graphics library.

One catch that you might run into is the need for a Graphics class instance when you call GraphPane.AxisChange(). Note that this class instance is really only used for sizing of text, etc. It is not used for rendering images. Therefore, you can just create a graphics instance from a small bitmap. The following is a simple code example that creates a graph and saves it to a file called zedgraph.png. To implement this example, follow these steps:

  1. Create a new C# console project in visual studio
  2. Add zedgraph.dll as a reference to the project
  3. Add System.Drawing.dll as a reference to the project
  4. Enter the following code for the Program.cs file
using System;
using System.Collections.Generic;
using System.Text;
using ZedGraph;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main( string[] args )
      {
         GraphPane myPane = new GraphPane( new RectangleF( 0, 0, 640, 480 ),
                     "Graph Title", "X Title", "Y Title" );

         PointPairList ppl = new PointPairList();
         for ( double x = 0; x < 50.0; x+=1.0 )
         {
            double y = Math.Sin( x / 10.0 );
            ppl.Add( x, y );
         }

         LineItem myCurve = myPane.AddCurve( "Sine Wave", ppl, Color.Blue, SymbolType.Diamond );

         Bitmap bm = new Bitmap( 1, 1 );
         using ( Graphics g = Graphics.FromImage( bm ) )
            myPane.AxisChange( g );
         // For ZedGraph 4.3, the next line is: myPane.Image.Save( @"zedgraph.png", ImageFormat.Png );
         myPane.GetImage().Save(@"zedgraph.png", ImageFormat.Png);
      }
   }
}
Personal tools