Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  Chart Success Part 5 - Line Graph  »  Line Joins and Grid Lines
 »  Home  »  Windows Development  »  Graphics  »  Chart Success Part 5 - Line Graph  »  Line Joins and Grid Lines
Chart Success Part 5 - Line Graph
by Ged Mead | Published  06/06/2006 | .NET Newbie Graphics | Rating:
Line Joins and Grid Lines

Line Joins

   The power of the GraphicsPath now becomes more obvious.   In order to add a small circle - or rectangle, square or even text - in between each line segment we only need to make three tiny tweaks to the code.  The first tweak adds the initial circle at the very start of the chart line; the second tweak is inserted into the loop so that a small circle is added to the start of each subsequent line segment;  the third tweak pops a circle on the end of the final line segment.

   Check out the following code snippet, which forms part of the original DrawTheLine procedure.   I have highlighted in red the three new lines.   All other code in that procedure remains unchanged.

 '  Create a GraphicsPath to hold the line info
        Dim MyPath As New GraphicsPath

        ' Manually add the first circle to the path
        MyPath.AddEllipse(XPosStart - 2, YPosStart - 2, 4, 4)

        '  Manually add the first line to the Path
        MyPath.AddLine(XPosStart, YPosStart, XPosEnd, YPosEnd)
     
            For i As Integer = 1 To UBound(Sales) - 1
                '  Update the X and Y positions for the next value:
                '  Move start point one line width to the right
                XPosStart = XPosEnd
                '  Move end point one line width to the right
                XPosEnd = CInt(XPosStart + LineWidth)
                ' Assign YPosStart the 'old' value of Y
                YPosStart = YPosEnd
                ' Assign YPosEnd the next the next scaled Sales figure
                YPosEnd = CInt(Sales(i + 1) * VertScale)

                '  Add next circle
              
  MyPath.AddEllipse(XPosStart - 2, YPosStart - 2, 4, 4)
                '  Add the next line segment to the GraphicsPath
                MyPath.AddLine(XPosStart, YPosStart, XPosEnd, YPosEnd)
            Next

            '  Finally, manually add the last circle
          
  MyPath.AddEllipse(XPosEnd - 2, YPosEnd - 2, 4, 4)

   The AddEllipse method adds a circle with a diameter of 4 pixels to the GraphicsPath.   The X and Y positions of the circle are offset by a value of 2 pixels so that it is placed midway between the end of one line segment and the start of the next.

  You can change the circles into squares by replacing each AddEllipse line with this:

          MyPath.AddRectangle(New Rectangle(XPosEnd - 2, YPosEnd - 2, 4, 4))

Grid Lines

   Although by definition a grid comprises both horizontal and vertical lines, I have chosen to create two separate procedures, one for the horizontal grid lines and the other for the verticals.   You can then decide if you want both sets of gridlines to be used.  In a very small PictureBox, having both sets of lines can be distracting and you might want to give the user the choice of horizontal only, vertical only, both or none.  

Horizontal Grid Lines

   Based on what we have covered so far in this article, I hope you will find the following procedure, which draws a set of horizontal grid lines, fairly easy to follow:

   Private Sub DrawHorizontalLines()
        '  Calculate vertically equal gaps
        Dim VertGap As Integer = CInt(VertLineLength / 10)

        '  Set the Start and End points
        '  = Left and right margins on the baseline
        Dim StartPoint As New Point(LeftMargin + 3, PBLineChart.Height - BaseMargin)
        Dim EndPoint As New Point(PBLineChart.Width, PBLineChart.Height - BaseMargin)

        '  Initial settings
        Dim LineStart As New Point(StartPoint.X, StartPoint.Y - VertGap)
        Dim LineEnd As New Point(EndPoint.X, StartPoint.Y - VertGap)

        Dim ThinPen As New Pen(Color.LightGray, 1)

        For i As Integer = 1 To 10
            '  Draw a line
            g.DrawLine(ThinPen, LineStart, LineEnd)

            '  Reset Start and End Y positions, moving up the vertical line
            LineStart.Y -= VertGap
            LineEnd.Y -= VertGap
        Next

        ThinPen.Dispose()

    End Sub

   The procedure is very similar to that which we used to create the tickmarks on the vertical axis.  In fact, as you can probably tell, I've simply recycled that code, changing the start and end points, omitting the text and using a thinner pen in a light color.

Vertical Grid Lines

   In the same way, I have used the code that draws the Month names and tweaked it so that it draws vertical lines all the way across the chart:

 Private Sub DrawVerticalGridLines()
        Dim ThinPen As New Pen(Color.Bisque, 1)

        '  Calculate length of baseline drawn by the code above
        BaseLineLength = PBLineChart.Width - (LeftMargin + RightMargin)
        '  Calculate the width of each line segment
        LineWidth = (BaseLineLength / Sales.Length)

        '  Set the start point of the first string
        Dim LineStartX As Integer = CInt(LeftMargin + 30)

        For i As Integer = 0 To Months.Length - 1
            g.DrawLine(ThinPen, LineStartX, TopMargin, LineStartX, PBLineChart.Height - (BaseMargin + 4))

            '  Move start point along to the right
            LineStartX += CInt(LineWidth)
        Next

        ThinPen.Dispose()

    End Sub

   The only substantial difference being the replacement of DrawString with DrawLine, assigned with appropriate parameter values.

Final Display

   Add a call to these two procedures to the button click event.

    Private Sub btnDraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDraw.Click
        DrawOutline()
        DrawHorizontalLines()
        DrawVerticalGridLines()
        DrawTheLine()
        ShowMonths()
        FinalDisplay()
    End Sub

   Note that the gridlines are drawn before the actual Sales figures line is drawn.   This is important, otherwise the gridlines will tend to erase the sales line as it passes over it and makes it look unfinished.

   But finished we are!   A fairly basic but usable Line Chart, which you can alter or enhance in many ways as needed.

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 06/19/2006)
Rating
Thank you for this aricle, it was of great help to me. One question:
I am able to draw lines with the mouse on the graph and these must stay there, even after the graph is updated. How to go about?
Thanks!
 
Comment #2  (Posted by an unknown user on 06/19/2006)
Rating
Thank you for this aricle, it was of great help to me. One question:
I am able to draw lines with the mouse on the graph and these must stay there, even after the graph is updated. How to go about?
Thanks!
 
Comment #3  (Posted by Ged Mead on 06/19/2006)
Rating
Hi, You can continue in the same way by drawing your lines using DrawLine methods on the bitmap that is used and assigned to the PictureBox. If it is a single simple line you can update the bitmap on the mouse up event. If it is more complex you may need to use the DrawPath method again, saving the various mouse clicks along the way (it's fiddly but can be done).
There is a recent FAQ by Sp!ke on Persistence which you might also find of interest. You can read it here: http://www.vbcity.com/forums/faq.asp?fid=41&cat=Graphics&#TID128254
 
Comment #4  (Posted by Mike Brewster on 06/21/2006)
Rating
Thank Mr. Mead for a great tutorial. As a newbie to .NET, I am enjoying the difficulties from unlearning old school to learn new school stuff, such as this. ;-)

With that said, I may not fully understand some of your build notes. Are you in indicating that a class object be created called GraphicsPath with only the for interation in it?

Do you happen to have a ZIP build of this? I ask as the chart shows only a horizontal line at 1000 with the respective "points" as specified. I'm sure I'm missing something writing the code for DrawTheLine.

Any insight or comments is greatly appreciated. Thank you!
 
Comment #5  (Posted by an unknown user on 06/21/2006)
Rating
Hi Mike, Thanks for the feedback. I will upload a zipped sample solution by the end of the week, so you can see how the whole thing comes together.
 
Comment #6  (Posted by Ged Mead on 06/22/2006)
Rating
I have now uploaded a demo solution using VB.NET 2003. I hope this will help you to analyze the code in the article.
 
Comment #7  (Posted by Mike Brewster on 06/22/2006)
Rating
Thank Mr Mead! It is what I expected, I had the DrawTheLine coded incorrectly. I also notice your use of "try", though i didn't see it commented in the writing, is this strictly to catch the exception?. Also, if I wanted to have an additional line plotted, I assume referencing additional Sales arrays will do the trick. Again, thank you for a great tutorial!
 
Comment #8  (Posted by an unknown user on 06/27/2006)
Rating
high quality work, no shortcuts
 
Comment #9  (Posted by an unknown user on 06/30/2006)
Rating
Thanks Ged Meat for a wonderful Tutorial. I have one problem. When i am saving the chart. it not getting displayed. Can u suggest any solution for this

 
Comment #10  (Posted by Vimal Raj on 07/03/2006)
Rating
Wonderful Tutorial.When I am saving the graph in Jpeg,or any format the graph is not showing properly. In background fully its black. Can u help me out.
 
Comment #11  (Posted by Jimmie Missfeldt on 07/12/2006)
Rating
Great post. I had alot of help with it to draw my graph.

I translated all of it into C# though and came across a few problems with the VertScale on drawing the line.

I am still not quite sure from where in the translation the problem came but I got a flat line in the bottom of my graph. am using a hard size on the graph so I took the Scaling to Sales[1] * scaling (where scaling = 0.2) and it all came out good.

just a tip for you C# nerds out there who couldn't find any other graph tutorial ;)
 
Comment #12  (Posted by Bob Goh on 07/24/2006)
Rating
Excellent and well wriiten. Although my current job require me to build a complex time-distance diagram, after going through your article (1-5), it really equip me with some essential knowledges to kick start the develpoment. Thanks
 
Comment #13  (Posted by an unknown user on 08/01/2006)
Rating
Thank you!
 
Comment #14  (Posted by an unknown user on 09/29/2006)
Rating
excellent !!
 
Comment #15  (Posted by Cesar Parrales on 05/22/2007)
Rating
Mr. Mead. I having the problem that Mike say in his comment #5. You said in your comment #6 you uploaded a demo solution using VB.NET 2003.

My point is, haw can I get this solution?

I appreciate you help,

Thanks in advance.
 
Comment #16  (Posted by az on 05/31/2007)
Rating
Ok, however the chart lines fail to draw express edtion.
 
Comment #17  (Posted by an unknown user on 06/16/2007)
Rating
i am new in vb.net and this is very nicely created method for line grid

thanks
 
Comment #18  (Posted by an unknown user on 07/04/2007)
Rating
Very nice ! Thank You
 
Comment #19  (Posted by Julia Andrea Rodriguez Amaro on 07/28/2007)
Rating
Hello, I need to know where do you uploaded the sample for VB 2003. Thanks a lot!
 
Comment #20  (Posted by an unknown user on 10/05/2007)
Rating
Best C# tutorial, hands down! Please make more :)
 
Comment #21  (Posted by Nerea007 on 10/16/2007)
Rating
Thanks so much for the articles - I was struggling so much to find a good, comprehensive source for charts and graphics.

I'm having a little trouble with this section. My X-axis was not showing up and I was getting an error, so I changed 'PBBarChart' to 'PBLineChart' in these lines:

Dim StartPoint As New Point(LeftMargin, PBBarChart.Height - BaseMargin)

Dim VertLineLength As Integer = PBBarChart.Height - (BaseMargin + TopMargin)

g.DrawLine(LinePen, LeftMargin, PBBarChart.Height - BaseMargin, _
PBBarChart.Width - RightMargin, PBBarChart.Height - BaseMargin)

And the X-axis appeared just like in your screen shot, but then I went to make the procedure DrawTheLine() and it just didn't work - I got a blue horizontal line at the 1000 mark.

Could you give me any pointers as to where I'm going wrong? There was some mention in the comments about a zip file of the code - maybe you can refer me to the link and I can compare what I have written to see where my mistake is.

Thanks!
 
Comment #22  (Posted by Ged Mead on 10/16/2007)
Rating
Hi, If you navigate to the final page of the article and then page down to the bottom you will see there a link to a zip file named Chart5.zip. This is the downloadable sample. (It is placed between the "Related Articles" section and the start of the Comments.)

 
Comment #23  (Posted by an unknown user on 02/11/2008)
Rating
Very, very helpful article. I'm trying to create graphical statistics for a call management package, the next step is to connect to a SQL server table for input. Thanks for the tutorial!
 
Comment #24  (Posted by an unknown user on 03/25/2008)
Rating
Great tutorial ... thousands of thanks cast to u ... =)
 
Comment #25  (Posted by kishore on 04/10/2008)
Rating
Excellent work. How can i show value of the sales near the elliptical region. Any solution is apreciable

thnx
 
Sponsored Links