ASP.NET - barchart - Asked By chitra ganapathy on 16-Jul-11 08:26 AM

hi, i want to draw bar chart in asp.net c# using bitmap. the values are getting from textbox...please suggest an idea
Ravi S replied to chitra ganapathy on 16-Jul-11 10:11 AM
HI

Generating the Bar chart

Data which is to be displayed on X axis and Y axis is stored in ArrayLists, and then the data is read from theseArrayLists for creating the required bar chart.

First, the ArrayLists are populated as follows:

Dim aMonths As ArrayList = New ArrayList()
aProfits As ArrayList = New ArrayList()
aMonths.Add("January")
aMonths.Add("February")
aMonths.Add("March")
aMonths.Add("April")
aMonths.Add("May")
aMonths.Add("June")
aMonths.Add("July")
aMonths.Add("August")
aMonths.Add("September")
aMonths.Add("October")
aMonths.Add("November")
aMonths.Add("December")

aProfits.Add(240500)
aProfits.Add(220950)
aProfits.Add(283500)
aProfits.Add(340000)
aProfits.Add(325750)
aProfits.Add(123456)
aProfits.Add(235621)
aProfits.Add(345235)
aProfits.Add(290451)
aProfits.Add(152345)
aProfits.Add(653456)
aProfits.Add(785620)

Once the data is populated, the chart can be generated by calling the method DrawBarGraph:

DrawBarGraph("Profits!", aMonths, aProfits)

DrawBarGraph is defined as follows:

Sub DrawBarGraph(ByVal strTitle As String, _
        ByVal aX As ArrayList, ByVal aY As ArrayList)
    Const iColWidth As Integer = 60, iColSpace As Integer = 25, _
          iMaxHeight As Integer = 400, iHeightSpace As Integer = 25, _
          iXLegendSpace As Integer = 30, iTitleSpace As Integer = 50
    Dim iMaxWidth As Integer = (iColWidth + iColSpace) * aX.Count + iColSpace, _
          iMaxColHeight As Integer = 0, _
          iTotalHeight As Integer = iMaxHeight + iXLegendSpace + iTitleSpace

    Dim objBitmap As Bitmap = New Bitmap(iMaxWidth, iTotalHeight)
    Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)
 
    objGraphics.FillRectangle(New SolidBrush(Color.White), _
                0, 0, iMaxWidth, iTotalHeight)
    objGraphics.FillRectangle(New SolidBrush(Color.Ivory), _
                0, 0, iMaxWidth, iMaxHeight)

    ' find the maximum value
    Dim iValue As Integer
    For Each iValue In aY
        If iValue > iMaxColHeight Then iMaxColHeight = iValue
    Next

    Dim iBarX As Integer = iColSpace, iCurrentHeight As Integer
    Dim objBrush As SolidBrush = New SolidBrush(Color.FromArgb(70, 20, 20))
    Dim fontLegend As Font = New Font("Arial", 11), _
        fontValues As Font = New Font("Arial", 8), _
        fontTitle As Font = New Font("Arial", 24)

     ' loop through and draw each bar
    Dim iLoop As Integer
    For iLoop = 0 To aX.Count - 1
        iCurrentHeight = ((Convert.ToDouble(aY(iLoop)) / _
               Convert.ToDouble(iMaxColHeight)) * _
               Convert.ToDouble(iMaxHeight - iHeightSpace))
        objGraphics.FillRectangle(objBrush, iBarX, _
        iMaxHeight - iCurrentHeight, iColWidth, iCurrentHeight)
        objGraphics.DrawString(aX(iLoop), fontLegend, _
           objBrush, iBarX, iMaxHeight)
        objGraphics.DrawString(Format(aY(iLoop), "#,###"), _
           fontValues, objBrush, iBarX, iMaxHeight - iCurrentHeight - 15)
        iBarX += (iColSpace + iColWidth)
    Next
    objGraphics.DrawString(strTitle, fontTitle, objBrush, _
          (iMaxWidth / 2) - strTitle.Length * 6, iMaxHeight + iXLegendSpace)
    'objBitmap.Save("C:\inetpub\wwwroot\graph.gif", ImageFormat.GIF) 

    objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
    objGraphics.Dispose()
    objBitmap.Dispose()
End Sub

This code will generate the bar chart and display it on the screen. Also, if required, the bar chart can be saved as an image, just uncomment the line below in the above code:

objBitmap.Save("C:\inetpub\wwwroot\graph.gif", ImageFormat.GIF)
Jitendra Faye replied to chitra ganapathy on 16-Jul-11 11:15 AM

The Microsoft Office Chart object can be used to achieve your goal.

 

The Microsoft Office Chart object is a part of Office Web Component and copied/registered to local computer when you install Microsoft Office.

 

How to use it in VB.NET?

Right-click Toolbox -> Choose items... -> COM tab -> Choose "Microsoft Office Chart 11.0"

Then the control named "Microsoft Office Chart 11.0" will appear in Toolbox.


You can drag&drop it to Form.


Demo project: http://www.codeproject.com/KB/graphics/ChartOWC.aspx

Simple Charts Using OWC (Office Web Component)

 

In addition, there are some third components used to render line graph/chart.


1. csXGraph ActiveX control, draw Line Graph, Bar Chart and Pie Chart

   http://www.chestysoft.com/xgraph/vbnetdemo.asp

    Usage and sample: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2432978&SiteID=1

 

2. Graphi - The Line Graph Component

   http://www.codeproject.com/cs/miscctrl/Graphi.asp

 

3. Create Dynamic Line Chart graph

   http://www.codeproject.com/useritems/Dynamic_Line_Chart.asp

 

4. Creating Line Chart For WebForms

   http://www.codeproject.com/aspnet/LineGraph.asp

Radhika roy replied to chitra ganapathy on 16-Jul-11 12:11 PM

if you don't have to build complex and interactive charts you could try Google Chart, it's super easy...

example:

<img src="http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World" /

produce:

alt text

http://code.google.com/apis/chart/

Radhika roy replied to chitra ganapathy on 16-Jul-11 12:19 PM
This script generates a series of horizontal bars in graph chart format, on an .aspx web page. 

To run the graph script is very simple. First save the following code into a file called dotnetgraph.ascx 


<script language="C#" runat="server">

    //********************************************************************************************
    // DotNetGraph, v1.0
    // Purpose: This page control generates a cross-browser compatible graph in HTML.
    //********************************************************************************************
    // Created on 4/29/01 Chris Goldfarb
    //
    // Feel free to make any changes to the code, but if you redistribute please keep a reference
    // to the original author.
    // 
    // Notes: The first version only supports vertical bar graphs.  More to follow!  Send
    // suggestions for improvement to cgoldfar@direcpc.com or christopher.goldfarb@intel.com
    // Reference the DotNetGraph.aspx page (code below) for a simple example on how to interface.
    //********************************************************************************************

    private String        _sXAxisTitle;
    private String        _sChartTitle;
    private Int32        _iUserWidth = 300;
    private String []    _sYAxisItems;
    private Int32 []    _iYAxisValues;

    public Int32 UserWidth {
        get { return _iUserWidth; }
        set { _iUserWidth = value; }
    }

    public Int32 [] YAxisValues {
        get { return _iYAxisValues; }
        set { _iYAxisValues = value; }
    }

    public String [] YAxisItems {
        get { return _sYAxisItems; }
        set { _sYAxisItems = value; }
    }

    public String XAxisTitle {
        get { return _sXAxisTitle; }
        set { _sXAxisTitle = value; }
    }

    public String ChartTitle {
        get { return _sChartTitle; }
        set { _sChartTitle = value; }
    }

    void Page_Load(Object sender, EventArgs e) {    
    
        // As long as we have values to display, do so
        if (_iYAxisValues != null) {
            
            // Color array
            String [] sColor = new String[9];
            sColor[0] = "red";
            sColor[1] = "lightblue";
            sColor[2] = "green";
            sColor[3] = "orange";
            sColor[4] = "yellow";
            sColor[5] = "blue";
            sColor[6] = "lightgrey";
            sColor[7] = "pink";
            sColor[8] = "purple";

            // Initialize the color category
            Int32 iColor = 0;

            // Display the chart title
            lblChartTitle.Text = _sChartTitle;

            // Get the largest value from the available items
            Int32 iMaxVal = 0;            
            for (int i = 0; i < _iYAxisValues.Length; i++) {
                if (_iYAxisValues[i] > iMaxVal)
                    iMaxVal = _iYAxisValues[i];
            }

            // Take the user-provided maximum width of the chart, and divide it by the
            // largest value in our valueset to obtain the modifier
            Int32 iMod = Math.Abs(_iUserWidth/iMaxVal);

            // This will be the string holder for our actual bars.
            String sOut = "";
            
            // Render a bar for each item
            for (int i = 0; i < _iYAxisValues.Length; i++) {

                // Only display this item if we have a value to display
                if (_iYAxisValues[i] > 0) {

                    sOut += "<tr><td align=right>" + _sYAxisItems[i] + "</td>";
                    sOut += "<td>" + RenderItem(_iYAxisValues[i], iMod, sColor[iColor]) + "</td></tr>";
                    iColor++;
                    
                    // If we have reached the end of our color array, start over
                    if (iColor > 8) iColor = 0;
                }
            }
            
            // Place the rendered string in the appropriate label
            lblItems.Text = sOut;
            
            // Drop in the Y Axis label
            lblXAxisTitle.Text = _sXAxisTitle;
        }
    }

    //****************************************************************************************
    // DotNetGraph.RenderItem Method
    //
    // Created 4/29/01 Chris Goldfarb
    //
    // Generates a horizontal bar graph for a given item
    //****************************************************************************************
    private String RenderItem (Int32 iVal, Int32 iMod, String sColor) {
        String sRet = "";
        sRet += "<table border=0 bgcolor=" + sColor + " cellpadding=0 cellspacing=0><tr>";
        sRet += "<td align=center width=" + (iVal * iMod) + " nobr nowrap>";
        sRet += "<b>" + iVal + "</b>";
        sRet += "</tr><td></table>";
        return sRet;
    }
        
</script>

<table>
    <tr>
        <td align=center>
            <asp:Label id=lblChartTitle runat=server />            
        </td>
    </tr>
    <tr>
        <td>
            <table border=1 bordercolor='#777777' cellspacing=0 cellpadding=0>
                <tr>
                    <td>
                        <table>
                            <asp:Label id=lblItems runat=server />
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td colspan=2 align=center>
            <asp:Label id=lblXAxisTitle runat=server />
        </td>
    </tr>
</table>

Then save the following in the same directory to a file called dotnetgraph.aspx 


<%@ Register TagPrefix="DNG" TagName="DotNetGraph" Src="DotNetGraph.ascx" %>

<script language="C#" runat="server">

    void Page_Load(Object sender, EventArgs e) {            
    
        // Declare our variables
        String [] sItems = new String[10];
        Int32 [] iValue = new Int32 [10];

        // Populate our variables
        sItems[0] = "Carrots";
        iValue[0] = 23;
        
        sItems[1] = "Peas";
        iValue[1] = 53;
        
        sItems[2] = "Celery";
        iValue[2] = 11;
        
        sItems[3] = "Onions";
        iValue[3] = 21;
        
        sItems[4] = "Radishes";
        iValue[4] = 43;
        
        // Set our axis values
        dngchart.YAxisValues = iValue;
        
        // Set our axis strings
        dngchart.YAxisItems  = sItems;            
        
        // Provide a title
        dngchart.ChartTitle  = "<b>Inventory Breakdown:</b>";
        
        // Provide an title for the X-Axis
        dngchart.XAxisTitle  = "(units display actual numbers)";        
        
    }
            
</script>

<html>
<body>
<!-- Note UserWidth is set "in-line".  It could just as easily been set on the page_load method. -->
<DNG:DotNetGraph id=dngchart UserWidth=200 runat=server />
</body>
</html>


Within this aspx page you will see we set all the quantities and labels for the graph within the Page_Load function. 

There is obviously plenty of scope for development in this section - for example, pulling these values directly from a database. But hopefully the elegant simplicity of these files will be a useful introduction to the concepts involved.

plz refer the link-

http://www.codetoad.com/asp.net_graph.asp
Devil Scorpio replied to chitra ganapathy on 16-Jul-11 02:44 PM
Hi Chitra,

Please refer the following complete code to draw bar chart using bitmap.

Request you to make change in width, height , space & other parameters as per ur need.

Sub DrawBarGraph(ByVal strTitle As String, ByVal aX As ArrayList, ByVal aY As ArrayList)
Const iColWidth As Integer = 60, iColSpace As Integer = 25, _
iMaxHeight As Integer = 400, iHeightSpace As Integer = 25, _
iXLegendSpace As Integer = 30, iTitleSpace As Integer = 50
Dim iMaxWidth As Integer = (iColWidth + iColSpace) * aX.Count + iColSpace, _
iMaxColHeight As Integer = 0, _
iTotalHeight As Integer = iMaxHeight + iXLegendSpace + iTitleSpace

Dim objBitmap As Bitmap = New Bitmap(iMaxWidth, iTotalHeight)
Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)

objGraphics.FillRectangle(New SolidBrush(Color.White), _
0, 0, iMaxWidth, iTotalHeight)
objGraphics.FillRectangle(New SolidBrush(Color.Ivory), _
0, 0, iMaxWidth, iMaxHeight)

' find the maximum value
Dim iValue As Integer
For Each iValue In aY
If iValue > iMaxColHeight Then iMaxColHeight = iValue
Next

Dim iBarX As Integer = iColSpace, iCurrentHeight As Integer
Dim objBrush As SolidBrush = New SolidBrush(Color.FromArgb(70, 20, 20))
Dim fontLegend As Font = New Font("Arial", 11), _
fontValues As Font = New Font("Arial", 8), _
fontTitle As Font = New Font("Arial", 24)

' loop through and draw each bar
Dim iLoop As Integer
For iLoop = 0 To aX.Count - 1
iCurrentHeight = ((Convert.ToDouble(aY(iLoop)) / _
Convert.ToDouble(iMaxColHeight)) * _
Convert.ToDouble(iMaxHeight - iHeightSpace))
objGraphics.FillRectangle(objBrush, iBarX, _
iMaxHeight - iCurrentHeight, iColWidth, iCurrentHeight)
objGraphics.DrawString(aX(iLoop), fontLegend, _
objBrush, iBarX, iMaxHeight)
objGraphics.DrawString(Format(aY(iLoop), "#,###"), _
fontValues, objBrush, iBarX, iMaxHeight - iCurrentHeight - 15)
iBarX += (iColSpace + iColWidth)
Next
objGraphics.DrawString(strTitle, fontTitle, objBrush, _
(iMaxWidth / 2) - strTitle.Length * 6, iMaxHeight + iXLegendSpace)
'objBitmap.Save("C:\inetpub\wwwroot\grap… ImageFormat.GIF)

objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
objGraphics.Dispose()
objBitmap.Dispose()
End Sub
Riley K replied to chitra ganapathy on 16-Jul-11 10:40 PM
You can go with fusion charts which is an opensource, it has got excellent rich graphic work,

all you need is to pass the DataSet to it.

follow this link

 http://www.fusioncharts.com/LiveDemos.asp