Showing posts with label Bar chart. Show all posts
Showing posts with label Bar chart. Show all posts

Sunday, 8 May 2011

Creating Bar Chart using C#

Creating Bar Chart in windows using C#
Introduction-
For making bar chart we will make use of ‘DrawRectangle’ in built function. because we have to first create a big rectangle defining the boundary of bar graphs. Parameters of DrawRectangle is :

1. Pen – This defines the color and style of border
2. Rectangle – Rectangle object to be created

Rectangle(int x, int y, int width,int height)

X and y are the co-ordinates of top left corner of rectangle. Width and height are width and height of rectangle.

Height = (weight of current array element *height of outer rectangle )/ maximum weight.
X coordinate is incremented by width of bars everytime a new bar is created.

Y co-ordinate is calculated by the following formula:
y = y coordinate of outer rectangle + height of outer rectangle – height of bar 
Code for DrawBarChart

private void DrawBarChart(PaintEventArgs e, int[] alWeight)
        {
            int numberOfSections = alWeight.Length;
            int lengthArea = 330;
            int heightArea = 280;
            int topX = 20;
            int topY = 20;
            int maxWeight = MaxValue(alWeight);
            int[] height = new int[numberOfSections];
            int total = SumOfArray(alWeight);
            Random rnd = new Random();
            SolidBrush brush = new SolidBrush(Color.Aquamarine);
            Pen pen = new Pen(Color.Gray);
            Rectangle rec = new Rectangle(topX, topY, lengthArea, heightArea);
            e.Graphics.DrawRectangle(pen, rec);
            pen.Color = Color.Black;
            int smallX = topX;
            int smallY = 0;
            int smallLength = (lengthArea / alWeight.Length);
            int smallHeight = 0;
            for (int i = 0; i < numberOfSections; i++)
            {
                brush.Color = Color.FromArgb(rnd.Next(200, 255),
           rnd.Next(255), rnd.Next(255), rnd.Next(255));
                smallHeight = ((alWeight[i] * heightArea) / maxWeight);
                smallY = topY + heightArea - smallHeight;
                Rectangle rectangle = new Rectangle
           (smallX, smallY, smallLength, smallHeight);
                e.Graphics.DrawRectangle(pen, rectangle);
                e.Graphics.FillRectangle(brush, rectangle);
                brush.Color = Color.FromKnownColor(KnownColor.Black);
                e.Graphics.DrawRectangle(pen, rectangle);
                smallX = smallX + smallLength;
            }
        }