Click here to Skip to main content
15,880,796 members
Articles / Web Development / ASP.NET

Using ZedGraph with ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.65/5 (10 votes)
8 Jun 2011CPOL4 min read 186K   4.2K   42   57
Web based usage of ZedGraph with ASP.NET

Introduction 

This article will help you get acquainted with Web based usage of Zed Graph. You will be able to use those graphs on your web pages.

Background

As you can't find any built in library for Charting in .NET, you have to use a third party source. What I found free and helpful is -- ZedGraph. 

Using the Code 

You need to reference 2 DLL files:

  1. ZedGraph.dll
  2. ZedGraph.web.dll

Also if want to make your web control visible in the toolbox, you need to create a tab in ToolBox and click Choose Item and then browse for ZedGraph.web.dll. You will get a control in your toolbox. Drag one to your design window.

There do exist several graphs, but I work on the following:

  1. Clustered Column 
  2. Stacked 
  3. Clustered Bar 
  4. Stacked Bar 
  5. Pie 
  6. Line

Add a reference to ZedGraph namespace:

C#
using ZedGraph; 

In the properties window, click on event and double click on RenderGraph to create an event for Rendering of Graph. This is where I write my whole code. You need to get the specific pane on which you are going to draw your graph. Following is the code to get that specific GraphPane object:

C#
// Get the GraphPane so we can work with it
GraphPane myPane = masterPane[0];

Once you get the reference to GraphPane object, you can set its X and Y axis title like this:

C#
// Set the title and axis labels        
myPane.XAxis.Title.Text = "X-Axis";
myPane.YAxis.Title.Text = "Y-Axis";

I have used some string and double arrays here to create some static points for drawing graph. String array here is used to create labels on X axis. I don't want to show 1,2,3… for months instead I want to show the name of months on X-axis. That’s why this label array has been created here.

C#
// Make up some data points
string[] labels = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", 
			"Aug", "Sep", "Oct", "Nov", "Dec" };

double[] xAxis = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
double[] x = { 10, 60, 50, 60,50, 90, 50, 90, 70, 80, 50, 30 };
double[] x2 = { 30, 40, 20, 30, 30, 60, 90, 90, 50, 80, 30, 70 };
double[] x3 = { 60, 60, 20, 20, 90, 30, 80, 60, 50, 80, 70, 0 };
double[] x4 = { 80, 50, 20, 20, 90, 80,30, 50, 60, 30, 80, 70 };
double[] x5 = { 90, 10, 20, 20, 20, 20, 50, 30, 90, 60, 70, 80 };    

You need to create an object for BarItem. Here we just declare an object:

C#
// Declare a BarItem:- Bar Item is used for creating a bar     
BarItem myCurve;

LineItem has been declared for drawing a line:

C#
// Declare a LineItem:- LineItem is used for creating a line     
LineItem oLineItem;

I have used switch to set different options for different graphs:

C#
switch (cboGraphType.SelectedValue)
        {
            case "Clustered Column":
            case "Stacked":

Here I have used AddBar method of GraphPane class. You need to supply a Caption that will be displayed on the legend (I used “Completed” for caption on legend). For vertical bar, you need to give Y values in the form of an array. Each item in the array will be considered as a point. Like here, the first bar is of 80 unit on Y axis and the second is of 50 and so on..

C#
// Generate a blue bar with "Completed" in the legend
myCurve = myPane.AddBar("Completed", null, x4, Color.Blue);

Here a gradient is created and filled inside bar. The first three parameters are color and the fourth one is angle:

C#
// Fill the bar with a Blue-white-Blue color gradient for a 3d look
myCurve.Bar.Fill = new Fill(Color.Blue, Color.White, Color.Blue, 0f);

This code is the same, but here I have created a red bar. This red bar is adjacent to each blue bar.

C#
// Generate a red bar with "Identified" in the legend
myCurve = myPane.AddBar("Identified", null, x3, Color.Red);
// Fill the bar with a red-white-red color gradient for a 3d look
myCurve.Bar.Fill = new Fill(Color.Red, Color.White, Color.Red, 0f);
break;

For clustered bar and stacked bar, the bar should be horizontal so here I have assigned the double array to X axis rather than Y axis.

C#
case "Clustered Bar":
case "Stacked Bar":
     // Generate a blue bar with "Completed" in the legend
     myCurve = myPane.AddBar("Completed", x4, null, Color.Blue);
     // Fill the bar with a Blue-white-Blue color gradient for a 3d look
     myCurve.Bar.Fill = new Fill(Color.Blue, Color.White, Color.Blue, 0f);

     // Generate a red bar with "Identified" in the legend
     myCurve = myPane.AddBar("Identified", x3, null, Color.FromArgb(132, 33, 99));
     // Fill the bar with a red-white-red color gradient for a 3d look
     myCurve.Bar.Fill = new Fill(Color.Red, Color.White, Color.Red, 0f);

     break;

A pie chart is created here. The chart fill is set to None to let it empty. After that, the legend’s position has been set using the location property. Legend.Position is set to LegendPos.Float to allow legend to be adjusted according to location supplied. Font size is set afterwards. After this IsHStack is set to false to make the legend appear vertical.

C#
case "Pie":
    // Fill the pane background with a color gradient
    myPane.Fill = new Fill(Color.White, Color.Goldenrod, 45.0f);
    // No fill for the chart background
    myPane.Chart.Fill.Type = FillType.None;
    // Set the legend to an arbitrary location
    myPane.Legend.Position = LegendPos.Float;
    myPane.Legend.Location = new Location
	(0.95f, 0.15f, CoordType.PaneFraction, AlignH.Right, AlignV.Top);
    myPane.Legend.FontSpec.Size = 10f;
    // IsHStack is use the create the legend items horizontally
    myPane.Legend.IsHStack = false;

Similar to that of BarItem, you can use PieIt<code>em. Here I created 12 slices, one for each month. The first parameter is the double value, second and third are color and the fourth is angle. The fifth one is the displacement of pie. You can have your pieitem out like a slice of pizza if you use some displacement like 0.2.

C#
// Add some pie slices
PieItem segment1 = myPane.AddPieSlice(x4[0], Color.Navy, Color.White, 45f, 0, "Jan");
PieItem segment2 = myPane.AddPieSlice(x4[1], Color.Purple, Color.White, 45f, 0, "Feb");
PieItem segment3 = myPane.AddPieSlice(x4[2], 
	Color.LimeGreen, Color.White, 45f, 0, "Mar");
PieItem segment4 = myPane.AddPieSlice(x4[3], 
	Color.SandyBrown, Color.White, 45f, 0, "Apr");
PieItem segment5 = myPane.AddPieSlice(x4[4], Color.Red, Color.White, 45f, 0, "May");
PieItem segment6 = myPane.AddPieSlice(x4[5], Color.Blue, Color.White, 45f, 0, "Jun");
PieItem segment7 = myPane.AddPieSlice(x4[6], Color.Green, Color.White, 45f, 0, "Jul");
PieItem segment8 = myPane.AddPieSlice(x4[7], Color.Yellow, Color.White, 45f, 0, "Aug");
PieItem segment9 = myPane.AddPieSlice(x4[8], 
	Color.YellowGreen, Color.White, 45f, 0, "Sep");
PieItem segment10 = myPane.AddPieSlice(x4[9], 
	Color.AliceBlue, Color.White, 45f, 0, "Oct");
PieItem segment11 = myPane.AddPieSlice(x4[10], 
	Color.AntiqueWhite, Color.White, 45f, 0, "Nov");
PieItem segment12 = myPane.AddPieSlice(x4[11], Color.Aqua, Color.White, 45f, 0, "Dec");
// Calculate the Axis Scale Ranges           

There is no obligation to call AxisChange() for manually scaled axes. AxisChange() is only intended to handle auto scaling operations. Call this function anytime you change, add, or remove curve data to ensure that the scale range of the axes are appropriate for the data range. This method calculates a scale minimum, maximum, and step size for each axis based on the current curve data. Only the axis attributes (min, max, step) that are set to auto-range (MinAuto, MaxAuto, MajorStepAuto) will be modified. You must call Invalidate() after calling AxisChange to make sure the display gets updated. This overload of AxisChange just uses the default Graphics instance for the screen. If you have a Graphics instance available from your Windows Form, you should use the AxisChange(Graphics) overload instead.

C#
masterPane.AxisChange(g);
// There is no need for pie chart to adjust X and Y axis. 
// So the rest of the code is irrelevant with regard to Pie Chart
return;
break;

For line, you need to use AddCurve method and use Xaxis double array for X-axis and x4 for Y-axis. SymbolType is used to create a symbol at a specific point. Here I want no symbol so I used SymbolType.None.

C#
case "Line":
    oLineItem = myPane.AddCurve("Completed", xAxis, x4, Color.Blue, SymbolType.None);
    oLineItem = myPane.AddCurve("Identified", xAxis, x3, 
		Color.FromArgb(132, 33, 99), SymbolType.None);
    break;
}

switch (cboGraphType.SelectedValue)
{
    case "Clustered Column":
    case "Stacked":

Here I set X-axis scale TextLabel, because I want to show Month name instead of numbers. For vertical bars, the bar base is X and for horizontal bars, the bar base is Y:

C#
// Set the XAxis labels
myPane.XAxis.Scale.TextLabels = labels;
// Set the XAxis to Text type
myPane.XAxis.Type = AxisType.Text;
// Make the bars Vertical by setting the BarBase to "X"
myPane.BarSettings.Base = BarBase.X;
break;
case "Clustered Bar":
case "Stacked Bar":
// Set the YAxis labels
myPane.YAxis.Scale.TextLabels = labels;
// Set the YAxis to Text type
myPane.YAxis.Type = AxisType.Text;
// Make the bars horizontal by setting the BarBase to "Y"
myPane.BarSettings.Base = BarBase.Y;
break;      

Here  MajorTic.IsBetweenLabels is set to false to avoid Tic's between labels:

C#
case "Line":
               // Set the XAxis labels
               myPane.XAxis.Scale.TextLabels = labels;
               // Set the YAxis to Text type
               myPane.XAxis.Type = AxisType.Text;
               // Draw the X tics at the labels
               myPane.XAxis.MajorTic.IsBetweenLabels = false;
               break;
       }

BarSettings.Type is used to set the type of bar. For clustered bar, it is Cluster and for stack it is Stack. AxisChange is used to handle auto scaling operation:

C#
switch (cboGraphType.SelectedValue)
      {
          case "Clustered Column":
          case "Clustered Bar":
              // Set the bar type to stack,
         // which stacks the bars by automatically accumulating the values
              myPane.BarSettings.Type = BarType.Cluster;
              break;
          case "Stacked":
          case "Stacked Bar":
              // Set the bar type to stack,
         // which stacks the bars by automatically accumulating the values
              myPane.BarSettings.Type = BarType.Stack;
              break;
     }

      // Fill the axis background with a color gradient
      myPane.Chart.Fill = new Fill(Color.White,Color.FromArgb(255, 255, 166), 45.0F);

      masterPane.AxisChange(g);
  }

That's all about how I create these graphs. If you have any questions, please let me know. Thanks.

Points of Interest 

The thing which is appealing while working with chart is the visible appearance of the chart. You feel good while working with code. With change of your parameter diagrams do change.

History

  • 6th May, 2009: Initial post 
  • 8th June, 2011: Updated source files mentioning how to utilize a datatable to bind with zed graph

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Pakistan Pakistan
Follow my blogging activities here:-
http://www.hellowahab.wordpress.com

Follow my professional activities here:-
http://www.linkedin.com/in/hellowahab

Follow my tweets here:-
http://twitter.com/#!/hellowahab

Follow my personal activities here:-
https://www.facebook.com/hellowahab

Comments and Discussions

 
QuestionHeight property Pin
klaydze18-Jan-12 14:42
klaydze18-Jan-12 14:42 
QuestionZedGraphImage Folder Clearing Pin
MalcolmR24-Oct-11 4:21
MalcolmR24-Oct-11 4:21 
QuestionMiss some point on the graph Pin
mona19903-Jul-11 15:21
mona19903-Jul-11 15:21 
GeneralMy vote of 5 Pin
Monjurul Habib8-Jun-11 8:19
professionalMonjurul Habib8-Jun-11 8:19 
GeneralImage labels Pin
Lo0ping20-Dec-10 23:32
Lo0ping20-Dec-10 23:32 
GeneralThat assembly does not allow partially trusted callers. !!! Pin
asedfred18-Oct-10 7:12
asedfred18-Oct-10 7:12 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
Wahab Hussain18-Oct-10 19:17
Wahab Hussain18-Oct-10 19:17 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
asedfred20-Oct-10 7:37
asedfred20-Oct-10 7:37 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
Wahab Hussain20-Oct-10 23:58
Wahab Hussain20-Oct-10 23:58 
AnswerRe: That assembly does not allow partially trusted callers. !!! Pin
Eli Hayon21-Oct-10 17:35
Eli Hayon21-Oct-10 17:35 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
Wahab Hussain21-Oct-10 19:05
Wahab Hussain21-Oct-10 19:05 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
asedfred25-Oct-10 8:49
asedfred25-Oct-10 8:49 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
MalcolmR24-Oct-11 4:33
MalcolmR24-Oct-11 4:33 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
Wahab Hussain24-Oct-11 19:07
Wahab Hussain24-Oct-11 19:07 
GeneralRe: That assembly does not allow partially trusted callers. !!! Pin
MalcolmR24-Oct-11 22:39
MalcolmR24-Oct-11 22:39 
Sorry I thought I had done so.

The error only appears when the site is published and file transferred to my hosted site.
The code in your example works fine when run locally using IIS.
Removal of the final line of code makes it work great when published. It does not appear to have any negative effect on the auto scaling as all graphs are well scaled. The code below renders a 4 curve graph of temperatures correctly. You can see it in action at www.bytemaster.co.uk

protected void zgwTemperature_RenderGraph(ZedGraph.Web.ZedGraphWeb webObject, System.Drawing.Graphics g, MasterPane pane)
{
GraphPane myPane = pane[0];
myPane.CurveList.Clear();
myPane.GraphObjList.Clear();
myPane.XAxis.Title.FontSpec.Size = 8;
myPane.YAxis.MajorTic.IsOpposite = false;
myPane.YAxis.MinorTic.IsOpposite = false;
myPane.YAxis.Scale.FontSpec.FontColor = Color.Black;
myPane.YAxis.Title.Text = "°C";
myPane.YAxis.Scale.MajorStep = 5;
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MajorGrid.Color = Color.Black;
myPane.YAxis.MajorGrid.Color = Color.Black;
myPane.XAxis.Scale.MinGrace = 0;
myPane.XAxis.Scale.MaxGrace = 0;
myPane.Fill = new Fill(Color.White);
myPane.Chart.Fill = new Fill(Color.GhostWhite);
myPane.XAxis.Type = AxisType.Date;
myPane.XAxis.Scale.Format = "HH:mm";
LineItem curve1 = myPane.AddCurve("Air", ppTempAir, Color.Red, SymbolType.None);
Fill fill = new Fill(Color.GhostWhite, Color.Red);
fill.RangeMin = 0;
fill.RangeMax = 1;
fill.Type = FillType.GradientByZ;
curve1.Line.GradientFill = fill;
LineItem curve2 = myPane.AddCurve("Ground", ppTempGnd, Color.Blue, SymbolType.None);
fill = new Fill(Color.GhostWhite, Color.Blue);
fill.RangeMin = 0;
fill.RangeMax = 1;
fill.Type = FillType.GradientByZ;
curve2.Line.GradientFill = fill;
LineItem curve3 = myPane.AddCurve("100mm depth", ppTemp100mm, Color.DarkSlateGray, SymbolType.None);
fill = new Fill(Color.GhostWhite, Color.DarkSlateGray);
fill.RangeMin = 0;
fill.RangeMax = 1;
fill.Type = FillType.GradientByZ;
curve3.Line.GradientFill = fill;
LineItem curve4 = myPane.AddCurve("300mm depth", ppTemp300mm, Color.LawnGreen, SymbolType.None);
fill = new Fill(Color.GhostWhite, Color.LawnGreen);
fill.RangeMin = 0;
fill.RangeMax = 1;
fill.Type = FillType.GradientByZ;
curve4.Line.GradientFill = fill;
// pane[0].AxisChange(g);
}
The remmed line was causing graph to fail when rendered.
QuestionHow to align Y and Y2 axis to zero line Pin
Murali8515-Aug-10 9:31
Murali8515-Aug-10 9:31 
GeneralY axis value is limited to max 1000 only. Pin
Avichal Agarwal2-Jun-10 20:26
Avichal Agarwal2-Jun-10 20:26 
GeneralRe: Y axis value is limited to max 1000 only. Pin
justapgmr3-May-11 10:41
justapgmr3-May-11 10:41 
GeneralRe: Y axis value is limited to max 1000 only. Pin
Wahab Hussain3-May-11 19:39
Wahab Hussain3-May-11 19:39 
GeneralDetermining all visible points Pin
Member 440636816-May-10 17:18
Member 440636816-May-10 17:18 
GeneralRe: Determining all visible points Pin
Wahab Hussain16-May-10 19:29
Wahab Hussain16-May-10 19:29 
GeneralRe: Determining all visible points Pin
Member 440636816-May-10 19:53
Member 440636816-May-10 19:53 
GeneralBar Font size Pin
kashamaleel29-Mar-10 7:59
kashamaleel29-Mar-10 7:59 
GeneralRe: Bar Font size Pin
Wahab Hussain30-Mar-10 6:24
Wahab Hussain30-Mar-10 6:24 
GeneralZedGraph 1st try [modified] Pin
pedroestrada5-Mar-10 4:48
pedroestrada5-Mar-10 4:48 

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.