Click here to Skip to main content
15,879,613 members
Articles / Web Development / ASP.NET
Article

Creating Line Chart For WebForms Using C#.

Rate me:
Please Sign up or sign in to vote.
3.45/5 (30 votes)
15 Apr 20042 min read 252.5K   5.1K   53   31
This article desscribes on how to create a line chart for web forms using C#.

Sample Image

Introduction

This article shows you how to create a line chart for web forms using C#. I think there are several third party components available for creating line chart and graphs. It wouldn't get you a knowledge on how internally it works. Hence I have created a line chart using GDI+ in C#. Besides this, you will be able to create a line chart in a quick manner.

Using the code

Below are the code for functions used to create the line chart:

Line2D.cs

Declaration section: declare these variables.

C#
private int m_Width = 700;     //Width of the rectangle container for graph.
private int m_Height = 400;   //Height of the rectangle container for graph.
private ArrayList m_XAxis;   //X-axis for the graph.
private ArrayList m_YAxis;  //Y-Axis for the graph.
private Color m_graphColor = Color.Red; //Color of the line graph.
private float m_XSlice = 1;            //Slice for X Axis.
private float m_YSlice = 1;           //Slice for Y Axis.
private Graphics objGraphics;        //Graphics Object.
private Bitmap objBitmap;           //Bitmap
private string m_XAxisText = "X-Axis";            //Default Title for X-Axis.
private string m_YAxisText = "Y-Axis";           //Default Title for Y-Axis.
private string m_Title = "Line Graph";          //Default Graph Title.
private Color m_TitleBackColor = Color.Cyan;   //Default Graph Title Back Color.
private Color m_TitleForeColor = Color.Green; //Default Graph Title Fore Color.

The next step is to create a property variable which facilitates the user to get or set values for the line chart.

C#
//Sets or Gets the Width for the rectangle container of graph.
public int Width
{
    get { return m_Width;}
    set 
    { 
        if ( value > 200)
        m_Width = value;
        //else
       //Width should be greater than 200.
    }
}

//Sets or Gets the Height for the rectangle container of graph.
public int Height
{
    get { return m_Height;}
    set 
    { 
        if ( value > 200)
          m_Height = value;
       //else
       //Height should be greater than 200.
    }
}

//Sets or Gets the X-Axis pixels for the graph.
public ArrayList XAxis
{
    set 
    { 
          m_XAxis = value;
    }
    get { return m_XAxis;}
}

//Sets or Gets the Y-Axis pixels for the graph.
public ArrayList YAxis
{
    set { m_YAxis = value;}
    get { return m_YAxis;}
}

//Sets or Gets the Color of the line Graph.
public Color GraphColor
{
    set { m_graphColor = value;}
    get { return m_graphColor;}
}

//Sets or Gets the X Axis Slice.
public float XSlice
{
    set { m_XSlice = value;}
    get { return m_XSlice;}
}

//Sets or Gets the Y Axis Slice.
public float YSlice
{
    set { m_YSlice = value;}
    get { return m_YSlice;}
}

//Sets or Gets the X-Axis Test.
public string XAxisText
{
    get { return m_XAxisText;}
    set { m_XAxisText = value;}
}

//Sets or Gets the Y-Axis Test.
public string YAxisText
{
    get { return m_YAxisText;}
    set { m_YAxisText = value;}
}

//Sets or Gets the title for the Graph.
public string Title
{
    get { return m_Title;}
    set { m_Title = value;}
}

//Sets or Gets the title Backcolor.
public Color TitleBackColor
{
    get { return m_TitleBackColor;}
    set { m_TitleBackColor = value;}
}

//Sets or Gets the Title ForeColor.
public Color TitleForeColor
{
    get { return m_TitleForeColor;}
    set { m_TitleForeColor = value;}
}

The above code snippet shows the following: creates Graphics object, initializes the Graph, draws rectangle region and fills the region, draws X-Axis line and Y-Axis line, draws Origin (0,0) point and sets Axis text and creates title.

C#
public void InitializeGraph()
{

    //Creating a bitmap image with given height and width.
    objBitmap = new Bitmap(Width,Height);

    //Getting the bitmap image into the graphics portion of the screen.
    objGraphics = Graphics.FromImage(objBitmap);

    //Filling the rectangle portion of the graphics with custom color.
    objGraphics.FillRectangle(new SolidBrush(Color.LightGray),0,0,Width,Height);

    //Drawing X-Axis line.
    objGraphics.DrawLine(new Pen(new SolidBrush(Color.Black),2),
                           100,Height - 100,Width - 100,Height - 100);

    //Drawing Y-Axis line.
    objGraphics.DrawLine(new Pen(new SolidBrush(Color.Black),2),
                           100,Height - 100,100,10);

    //Plotting Origin(0,0).
    objGraphics.DrawString("0",new Font("Courier New",10),
                           new SolidBrush(Color.White),100,Height - 90);

    //Sets Axis text.
    SetAxisText(ref objGraphics);

    //Sets the title for the Graph.
    CreateTitle(ref objGraphics);
}

This function creates Graph by calling SetPixel function which draws the line in the rectangle region. Pass Color for the line Graph as input parameter.

C#
public void CreateGraph(Color _GraphColor)
{
    GraphColor = _GraphColor;
    //Plotting the pixels.
    SetPixels(ref objGraphics);
}

This function gets the bitmap image of the graph drawn.

public Bitmap GetGraph()
{

    //Creating X-Axis slices.
    SetXAxis(ref objGraphics,XSlice);

    //Creating Y-Axis slices.
    SetYAxis(ref objGraphics,YSlice);

    return objBitmap;
}

This function draws the axis line for the Graph.

C#
private void PlotGraph(ref Graphics objGraphics, 
              float x1,float y1,float x2,float y2)
{
    objGraphics.DrawLine(new Pen(new SolidBrush(GraphColor),2),
        x1 + 100, (Height - 100) - y1 ,x2 + 100,(Height - 100) - y2  );
}

This function plots X and Y axis slices with given value ranges..

C#
private  void SetXAxis(ref Graphics objGraphics,float iSlices)
{
    float x1 = 100,y1 = Height - 110,x2 = 100,y2 = Height - 90;
    int iCount = 0;
    int iSliceCount = 1;

    for(int iIndex = 0;iIndex <= Width - 200;iIndex += 10)
    {
        if(iCount == 5)
        {
            objGraphics.DrawLine(new Pen(new SolidBrush(Color.Black)),
                x1+iIndex,y1,x2+iIndex,y2);
            objGraphics.DrawString(Convert.ToString(iSlices * iSliceCount),
                new Font("verdana",8),new SolidBrush(Color.White),
                x1 + iIndex - 10,y2);
            iCount = 0;
            iSliceCount++;
        }
        else
        {
            objGraphics.DrawLine(new Pen(new SolidBrush(Color.Goldenrod)),
                        x1+iIndex,y1+5,x2+iIndex,y2-5);
        }
        iCount++;
    }
}

private void SetYAxis(ref Graphics objGraphics,float iSlices)
{
    int x1 = 95; 
    int y1 = Height - 110;
    int x2 = 105;
    int y2 = Height - 110;
    int iCount = 1;
    int iSliceCount = 1;

    for(int iIndex = 0;iIndex < Height - 200;iIndex+=10)
    {
        if(iCount == 5)
        {
            objGraphics.DrawLine(new Pen(new SolidBrush(Color.Black)),
                x1 - 5, y1 - iIndex,x2 + 5,y2 - iIndex);
            objGraphics.DrawString(Convert.ToString(iSlices * iSliceCount),
                new Font("verdana",8),new SolidBrush(Color.White),
                60,y1 - iIndex );
            iCount = 0;
            iSliceCount++;
        }
        else
        {
            objGraphics.DrawLine(new Pen(new SolidBrush(Color.Goldenrod)),
                x1, (y1 - iIndex),x2,(y2 - iIndex));
        }
        iCount ++;
    }
}

This function plots the points (x,y) in the graph.

C#
private void SetPixels(ref Graphics objGraphics)
{
    float X1 = float.Parse(XAxis[0].ToString());
    float Y1 = float.Parse(YAxis[0].ToString());

    if(XAxis.Count == YAxis.Count)
    {
        for(int iXaxis = 0,iYaxis =0;(iXaxis < XAxis.Count - 1 
                   && iYaxis < YAxis.Count - 1);iXaxis++,iYaxis++)
        {
            PlotGraph(ref objGraphics,X1,Y1,
                 float.Parse(XAxis[iXaxis + 1].ToString()),
                 float.Parse(YAxis[iYaxis + 1].ToString()));
            X1 = float.Parse(XAxis[iXaxis + 1].ToString());
            Y1 = float.Parse(YAxis[iYaxis + 1].ToString());
        }
    }
    else
    {
        //X and Y axis length should be same.
    }
}

This function sets the text for both X and Y axis.

C#
private void SetAxisText(ref Graphics objGraphics)
{
    objGraphics.DrawString(XAxisText,new Font("Courier New",10),
        new SolidBrush(Color.LimeGreen),
        Width / 2 - 50,Height - 50);

    int X = 30;
    int Y = (Height / 2 ) - 50;
    for(int iIndex = 0;iIndex < YAxisText.Length;iIndex++)
    {
        objGraphics.DrawString(YAxisText[iIndex].ToString(),
            new Font("Courier New",10),new SolidBrush(Color.LimeGreen),
            X,Y);
        Y += 10;
    }
}

This function is used to set the Title text for the graph.

C#
private void CreateTitle(ref Graphics objGraphics)
{
    objGraphics.FillRectangle(new SolidBrush(TitleBackColor), 
               Height - 100,20,Height - 200,20);
    Rectangle rect = new Rectangle(Height - 100,20,Height - 200,20);
    objGraphics.DrawString(Title,new Font("Verdana",10),
               new SolidBrush(TitleForeColor),rect);
}

Code for the Webform1.aspx.cs

The code for the class file is over and now we need to create an instance of this file in a Web Form which needs line graph, and set appropriate properties. Here I'm using Score Comparison report as an example (India Vs. Pakistan) to draw a line graph to compare the runs scored by both teams using line graph.

C#
//Create an instance of line2D.cs file.
Line2D line2d = new Line2D();

//Set the height for the graph image.
line2d.Height = 400;

//Set the width for the graph image.
line2d.Width = 700;

//Set the Slices(partition in Axis) for X and Y Axis.
line2d.XSlice = 50;
line2d.YSlice = 10;

//Set the Title for both Axis.
line2d.XAxisText = "Runs";
line2d.YAxisText = "Overs"

//Set the Graph Title.;
line2d.Title = "India vs Pakistan";

//Set the Backcolor and forecolor for the graph title.
line2d.TitleBackColor = Color.Linen;
line2d.TitleForeColor = Color.HotPink;

//Initialize the graph object to draw.
line2d.InitializeGraph();

//Create two array list to  store the points.
ArrayList arX = new ArrayList();
ArrayList arY = new ArrayList();

arX.Add(0);arX.Add(120);arX.Add(150);arX.Add(175);arX.Add(210);
arY.Add(0);arY.Add(100);arY.Add(50);arY.Add(150);arY.Add(190);
line2d.XAxis = arX;
line2d.YAxis = arY;

//Create Firstline
line2d.CreateGraph(Color.LightCyan);

arX = new ArrayList();
arY = new ArrayList();
arX.Add(0);arX.Add(110);arX.Add(160);arX.Add(195);arX.Add(200);
arY.Add(0);arY.Add(10);arY.Add(90);arY.Add(150);arY.Add(160);
line2d.XAxis = arX;
line2d.YAxis = arY;

//Create Second Line.
line2d.CreateGraph(Color.Red);

Bitmap bmp = line2d.GetGraph();
bmp.Save(Response.OutputStream,ImageFormat.Jpeg);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionthis works in IE only. Pin
randyhunt30-May-14 10:13
randyhunt30-May-14 10:13 
Questionbakwas Pin
Member 865260023-May-12 23:07
Member 865260023-May-12 23:07 
GeneralHow to set the Slices? Pin
aswathy.s.881-May-11 23:37
aswathy.s.881-May-11 23:37 
GeneralVery Good Pin
aswathy.s.8828-Apr-11 1:01
aswathy.s.8828-Apr-11 1:01 
GeneralGood Job Pin
timi2shoes3-Feb-09 10:45
timi2shoes3-Feb-09 10:45 
GeneralNice Pin
Pooya Musavi19-Oct-07 8:14
Pooya Musavi19-Oct-07 8:14 
Generalnice article Pin
Pooya Musavi19-Oct-07 8:08
Pooya Musavi19-Oct-07 8:08 
Generalproblem in this line chart source code Pin
Patilvaishalimangesh15-Jan-07 19:35
Patilvaishalimangesh15-Jan-07 19:35 
GeneralConverted from c# Pin
FFunsoft9-Nov-06 6:02
FFunsoft9-Nov-06 6:02 
GeneralVB .net code does not show the graph curves Pin
sheetalap29-Oct-06 13:35
sheetalap29-Oct-06 13:35 
GeneralVB.NET Pin
ddmma21-Jun-06 5:12
ddmma21-Jun-06 5:12 
GeneralHotspots (hyperlinks) Pin
elbowpipe9-May-06 0:28
elbowpipe9-May-06 0:28 
GeneralRe: Hotspots (hyperlinks) Pin
ddmma21-Jun-06 5:14
ddmma21-Jun-06 5:14 
Try to use MAP AREAS with dynamic values Smile | :)
GeneralCreate graph with other objects in the same page Pin
Leandro Engel11-Apr-05 7:02
Leandro Engel11-Apr-05 7:02 
GeneralRe: Create graph with other objects in the same page Pin
nigelxx18-Oct-07 10:51
nigelxx18-Oct-07 10:51 
GeneralRe: Create graph with other objects in the same page Pin
3sL29-Oct-08 23:09
3sL29-Oct-08 23:09 
QuestionHow to change the Scale x-axis as a month(1-12) Pin
hkebreab18-Jan-05 5:33
hkebreab18-Jan-05 5:33 
AnswerRe: How to change the Scale x-axis as a month(1-12) Pin
blyon1-Mar-05 14:36
blyon1-Mar-05 14:36 
Questionhow to use those function Pin
achan9012-Jun-04 9:44
achan9012-Jun-04 9:44 
GeneralJob Pin
Vasu Cherlopalle20-May-04 12:20
Vasu Cherlopalle20-May-04 12:20 
GeneralGood Stuff Pin
Kant16-Apr-04 9:48
Kant16-Apr-04 9:48 
GeneralNice job... Pin
MicrosoftBob16-Apr-04 0:54
MicrosoftBob16-Apr-04 0:54 
GeneralRe: Nice job... Pin
Ray Cassick16-Apr-04 7:28
Ray Cassick16-Apr-04 7:28 
GeneralRe: Nice job... Pin
MicrosoftBob16-Apr-04 14:44
MicrosoftBob16-Apr-04 14:44 
GeneralRe: Nice job... Pin
hkebreab18-Jan-05 5:36
hkebreab18-Jan-05 5:36 

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.