Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

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

Ged Mead (XTab) is a Microsoft Visual Basic MVP who has been working on computer software and design for more than 25 years. His journey has taken him through many different facets of IT. These include training as a Systems Analyst, working in a mainframe software development environment, creating financial management systems and a short time spent on military laptop systems in the days when it took two strong men to carry a 'mobile' system.

Based in an idyllic lochside location in the West of Scotland, he is currently involved in an ever-widening range of VB.NET, WPF and Silverlight development projects. Now working in a consultancy environment, his passion however still remains helping students and professional developers to take advantage of the ever increasing range of sophisticated tools available to them.

Ged is a regular contributor to forums on vbCity and authors articles for DevCity. He is a moderator on VBCity and the MSDN Tech Forums and spends a lot of time answering technical questions there and in several other VB forum sites. Senior Editor for DevCity.NET, vbCity Developer Community Leader and Admin, and DevCity.NET Newsletter Editor. He has written and continues to tutor a number of free online courses for VB.NET developers.

 

View all articles by Ged Mead...
Introduction

Outline

   As in the previous articles, the chart will be displayed in a PictureBox control.   Although it would be easy - easier in some ways - to simply plaster the chart onto the surface of the form itself, I think it is more realistic to house it inside some kind of container control because a chart is most often just one part of a range of information displayed to the user.   It also lends itself more easily to the situation where you want to take user input on screen and to use that data directly to draw or redraw the chart.

    For convenience, we will create some sample data at the start of the project.  In a real world scenario, you will probably gather this data from a data source of some kind, either one that has been previously saved to file or directly from the user on screen.    If you want to adjust the code in this article to take in data at runtime, you will find an example of how this can be done in Part 3 of this series.

Getting Started

   Add a form to a project and name it LineChartDemo.  Make the form size something in the region of 640 by 480.   Drag  a PictureBox on to the form from the ToolBox and drag its left, top and right borders so that they are very close to the edge of the form.   Drag the bottom of the PictureBox so that the PictureBox height is approx 80% of the form's height.   Set the PictureBox's Anchor property to include all four sides, Top, Bottom, Left and Right.  Set its BorderStyle property to the selection your prefer; I have used Fixed3D in the screenshot examples.  Name it "PBLineChart".

  Now, add a button to the form and place it down at the bottom right hand corner.   Change its Anchor property from the default setting to Bottom and Right.   These changes to the Anchor properties of the two controls mean that the PictureBox will resize usefully if the size of the form is changed and the button will remain anchored down in the left hand corner where you want it to be. 

   At the very top of the form, insert the following:

    Option Strict On
   Imports System.Drawing.Drawing2D

  The first line, as you probably know, is good practice (although it makes some of the code more unwieldy) and helps to avoid tricky conversion errors between the various Types .  The second line allows us access to all the methods in the Drawing2D class, some of which we will use to create the various lines and shapes in the chart.

 The Sample Data  

    Our sample data is very basic - 12 months of the year to be displayed on the horizontal axis and some figures to represent sales per month to be set against the vertical axis.   The two sets of data can conveniently be stored in two separate arrays;  Array "Months" to store the names, Array "Sales" to hold the figures.   As mentioned above, this is simply a convenience to enable us to get on with the business of drawing without getting too bogged down with data handling.

     Inside the "Public Class LineChartDemo" class code, enter the following code which creates the two arrays and populates them with the demo data in one step:

    Dim Months() As String = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", _
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
   
Dim Sales() As Integer = {835, 314, 672, 429, 715, 642, _
    153, 699, 622, 901, 345, 655}

Variables

    Much of the fiddly setting up of a chart involves deciding or calculating margins and lengths of lines, etc.   Some of these can be hard coded at design time - items such as the number of pixels to inset the start of the graph lines.   Others are better calculated dynamically -  things like the length of the baseline which can grow or shrink as the containing form's size is changed.

   The following code either sets up the hard coded values of variables or creates variables ready to be assigned appropriate values later when the application is run.   Place it below the code that instantiated the arrays.  

    '  ~~  Variables for margins and outlines, etc ~~
    '  # of pixels Y-Axis is inset from PicBox Left
    Dim LeftMargin As Integer = 35
    '  # of Pixels left unused at right side of PicBox
    Dim RightMargin As Integer = 15
    '  # of pixels above base of picturebox the X-Axis is placed
    Dim BaseMargin As Integer = 35
    '  Margin at Top
    Dim TopMargin As Integer = 10
      
    '  Variable to hold length of vertical axis
    Dim VertLineLength As Integer
    '  Variable to hold length of horizontal axis
    Dim BaseLineLength As Integer
    '  Variable to store length of each line segment
    Dim LineWidth As Double

    As in earlier examples, we are going to use the double buffering technique to create the chart in the background and "paste" it into the PictureBox once it is all ready and good to go.    Of course, we don't actually paste it in the traditional sense; what we do is to assign the completed chart drawing as the image for the PictureBox.  If you want to review how this works, you can find further explanation on Page 3 of Part 2 of this series. 

   We will create the Graphics object and Bitmap object in the next lines of code:

    '  ~~  Bitmap and Graphics Objects  ~~
    '  A variable to hold a Graphics object

    Dim g As Graphics
    '    Next, create a Bitmap object which is
    '    the same size and resolution as the PictureBox

    Dim bmap As Bitmap

    With that code all in place, we are ready to move on to the business of actually drawing the chart.   We will break the tasks into a series of procedures.   If you decide to recycle the sample code for your own purposes later, you will find it quite easy to make the necessary changes and can improve the procedures by passing parameters in place of some of the hard coded values I have used for demonstration purposes.

 

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
 
Comment #26  (Posted by an unknown user on 06/25/2008)
Rating
It was of great help
 
Comment #27  (Posted by Heruki Otsasori on 10/12/2008)
Rating
no matter which site you set as your default. ,
 
Comment #28  (Posted by Nick on 10/12/2008)
Rating
It works because reputable writers make links to things ,
 
Comment #29  (Posted by an unknown user on 11/19/2008)
Rating
A minor mistake in the article, the VertLineLength variable is Dimmed twice which causes the graph line to be drawn incorrectly. Otherwise an excellent article and very useful.
 
Comment #30  (Posted by an unknown user on 12/01/2008)
Rating
this is something i was looking for...
a beginners guide.. thanks!
 
Comment #31  (Posted by an unknown user on 01/19/2009)
Rating
Easy to follow and gives a good illustration of the concepts involved
 
Comment #32  (Posted by Naresh Kumar Prajapati on 03/17/2009)
Rating
Excellent Article yaar , good job. but i think u missed one line in ur DrawTheLine() subroutine which is
VertLineLength = PictureBox1.Height - (BaseMargin + TopMargin)
please have a look
 
Comment #33  (Posted by an unknown user on 05/09/2009)
Rating
i went through this artical,how ever i ddint use it so far but i m going to use it surely...

Thanks Man
 
Comment #34  (Posted by an unknown user on 08/25/2009)
Rating
Great work! Thank you.
 
Comment #35  (Posted by an unknown user on 09/23/2009)
Rating
i have searched many websites for source code of showing but none of these are good like this
 
Comment #36  (Posted by knockNrod on 09/24/2009)
Rating
First, excellent tutorial, thank you. Wished I had seen this a long time ago when I was first getting into GDI+.

The reason I came to this site was to look for a way to add points to a line graph, rather than line segments. The reason being that line segments tend to re-initialize the dots in a dotted line. Too many line segments converts a dotted line into a solid one.

I doubt you still monitor this article, given the date, although it's as relevant today as then, so if you are, do you have any suggestions on how to draw a many-point, dotted line graph?
 
Comment #37  (Posted by Ged on 09/25/2009)
Rating
Hi, I do try and monitor my articles, although I don't often find the time to respond to all the queries.
Yours, however, might be a relatively easy one.
You can set the dash pattern on the Pen object that you use for the DrawLine method.
Something like:
Dim DashPen as New Pen
DashPen = New Pen(Color.Black, 2)
DashPen.DashStyle = DashStyle.DashDotDot

g.DrawLine(DashPen, New Point(12,12), New Point(45,76))

NB. This is Air Code, but I think it's fairly accurate.
Give that a try and see if it works for you.
 
Comment #38  (Posted by JeywinLizy on 11/02/2010)
Rating
After a lot of search this article was of great help to me to plot the graph.

I get a problem and request your help on this.
I have now translated it to C#(working in Framework 2.The graph gets plotted as a flat line at the bottom of X-axis.
Pls help me out on this.
 
Comment #39  (Posted by Johnie on 05/11/2011)
Rating
Kewl you should come up with that. Ecxleelnt!
 
Comment #40  (Posted by Buy cheap OEM software on 09/29/2011)
Rating
H9pjPS It's straight to the point! You could not tell in other words! :D
 
Sponsored Links