Easy way to plot graphs with C# and Visual Studio 2010

Ola, amigos! Here I am again to another tutorial. This time I’m going to give you a brief tutorial teaching you how to plot graphs using a component called Chart, its recommended for you to take a look at its documentation before.

first

Well, for almost for years developing in C#, last month was the first time I ended up drawing graphs in an application I’m developing. After a couple of hours looking at the internet, I found an easy way to do it. You only need to add the coordinates, x and y, or only one of those and that’s it. It’s done!

So, here we go!
I’ll go through this step-by-step by the way.

I first created a new application, added a button and the Chart component.

chart

It looked like this.

So, before start coding, let’s create a collection. But, what is a collection? In simple words, a collection is your graph, the Chart component gives you the opportunity to plot more than one graph in the same place, thus a collection is a list of coordinates that you be shown to you.

Go to the Chart property called Series and add a new collection.
PS. Probably there will be one already added, if you want to plot only one graph, you can for sure use and dont need to add a new one, just check on its name, it will be important to our code.

chart2

You can see that I have now two collection, so I will draw one graph in blue and the second one in red.

Since our application is built, let’s start coding.
Open up the click method of your button by double clicking and follow the code bellow.

private void button1_Click(object sender, EventArgs e) { Random rdn = new Random(); for (int i = 0; i < 50; i++) { chart1.Series["test1"].Points.AddXY (rdn.Next(0,10), rdn.Next(0,10)); chart1.Series["test2"].Points.AddXY (rdn.Next(0,10), rdn.Next(0,10)); } chart1.Series["test1"].ChartType = SeriesChartType.FastLine; chart1.Series["test1"].Color = Color.Red; chart1.Series["test2"].ChartType = SeriesChartType.FastLine; chart1.Series["test2"].Color = Color.Blue; }

As you could see, I just random a few numbers and added to my both series.

Below the for there are 4 lines of code where I set up how I’d like my graphs to be like. If you dont want a line graph, you can just change the enumerator SeriesChartType.

That’s the result. It’s a little bit weird cause of my coordinates, but I just wanted to show you how simple is that.

chart3

That’s it for now!

Pretty simple, huh?

If you prefer, you can find the whole application here.

Anything you’d like to add, please use the comment area below.

.net

Thanks for the attention. Smile

180 comments

    1. Sure, you just have to add another Serie. It’s as simples as a single post.
      You can also configure the other Serie with a different color.

    1. Well, I haven’t tried yet! Is there any component called Chart in VS2008?
      Or another option, have you read anything about ZedGraph? It’s another easy way to plot graphs.
      I’m thinking about write a tutorial about it next weekend, but it’s pretty simple.

  1. trying this out. it is what im looking for. but i cannot find that chart option to add the Chart component, any ideas? thanks

  2. Error 1 The name ‘SeriesChartType’ does not exist in the current context C:\Users\Can\Documents\Visual Studio 2008\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Form1.cs 35

    give this error, thanks for help

    1. Hello Felipe.
      Hos to put hh:mm:ss in the X axis by programming?
      I using a numericUpDown as range for my Timer or my X axis.
      The numericUpDown’s range is from 10 to 7200.
      I need the X axis appear like this: (sample numericUpDown.Value = 120)
      00:00 00:10 00:20 00:30 00:40 00:50 01:00 01:10 01:20 01:30 01:40 01:50 02:00
      But (sample numericUpDown.Value = 5780)
      00:00:00 00:08:00 00:16:00 00:24:00 00:32:00 00:40:00 00:48:00 00:56:00 01:04:00 01:12:00 01:20:00 01:28:00 01:36:00

      Thanks in advance,
      silvio pontes

      1. Hello Silvio,

        Could you do that? I have no idea how to put that but we can talk and perhaps I can help you.
        Add me, my skype is: gen7il

        I’m sorry that took so long, I was on vacation.
        Regards,
        Felipe

  3. have created the chart,,,, but how it can be made dynamic i.e,, chart should be drawn on external user input or from an external file?
    thanks…..

    1. Well, what exactly do you mean by dynamic? For sure it can be drawn from an external file, you just need the data input.
      But I didnt understand how ‘dynamic’ your application should be.

      Sorry that took so long to answer.

  4. Hello,

    Do you know how to do parallel threads for plotting multiple line graphs?

    I am trying to display real time data with 256Hz input in one panel, but VS seems to lag a lot.

    Thanks!

    1. Well, I have something similar here, but for sure less than 256Hz. Have you seen another plot component called ZedGraph? Perhaps it can be faster.
      Sorry that took so long to answer.

  5. Thank you so much. I have 2 questions:
    1. Is there any way to clear the graph to draw a new one in the same position?
    2. How to add the units of the 2 axises?

    1. Hello, I’m sorry to answer after a long time.
      So, first of all, thanks for the comment.

      1. It’s possible to clear the graph, you just have the clear the correspondent .Series property of the chart, and then draw it again.
      2. I didnt understand what you mean by add units of the 2 axies? You mean for ex (m², cm, s, h)? If its that, you just have to write into label property.

      Hope my answers were clear enough.

      Regards

  6. How can I use plot a graph with given values from a datatable? (results of x co-ordinates and y co-ordinates)

    1. How are you reading those values form database? Which database are you using? Where do you have those values stored? If you have them in an array, all you have to do is a for loop and pass your values to the plot chart.

      If it was not helpful at all, please let me know. I’m always glad to help.

      Regards,
      Felipe

  7. Hi. How can i insert labels on the axis, and make them centered with the plot? I tried to add a title on design mode but i can’t put it in the right position.

    1. Hello!
      Well, to insert and set the label you can use the property .Font, I’m sure it’s something like:

      series.Font = new Font(Font.Name, Font.size, FontStyle).

      Hope it helps, if you still have problem with let it centered, let me know please.

      Regards,
      Felipe

      1. I’ve told you that i wanted to insert label but what i want is to insert a title on the axis. For instance, i wanna make a graph Hours per day and i want to put the title hours on the yaxis and hours on the xaxis.
        I’ve tried to creat a chart object on design mode and then do this:
        Axis axisx = new Axis(area, AxisName.X);
        axisx.Title = “axis”;
        Axis axisy = new Axis(area, AxisName.Y);
        axisx.Title = “axis”;
        but it does not work.

        Obrigado.

      2. Well, it’s not 100% clear in my mind what you want to do… do you have skype? Or any other way so we could talk.. it’s easier than here 🙂

    1. Well, when you have just a simple graph to plot, no more stuff to setup.. MSChart is an alternative, but if you want to “personalize” and plot multiple charts, Zedgraph is a more powerful tool…

      Best thing to do is try to use both, then one that fit better to your problem is the best solution 🙂

      Are you from Portugal? Just guesses from your name, lol.

      Regards, Felipe.

  8. Thank you. I will try to use Zedgraph then.

    You’re right, I’m Portuguese! 🙂

    Congratulations on you blog, the posts are pretty usefull and easy to understand.

    1. Any doubts, let me know.. I’m glad to help!

      And thanks a lot.. I’ve always wanted to visit Portugal, I’m from Brazil.. 🙂

      Regards, Felipe.

  9. You should, it’s a nice country!

    I never visited Brazil but i will for sure, maybe by the WorldCup 2014! 🙂

    Abraço, João.

  10. Yes I have them stored in an array, but I’m not sure about the code for it. Could you provide an example code?
    C# isn’t my strongest programming language and had to pick it up quickly to do my coursework.

    1. Hello Rai,

      Well, if you have all data stored in an array, you can plot using a for loop, like I did above…
      for (int i = 0; i < numbOfElements; i++)
      chart1.Series[0].Points.AddXY(xValue, yValue);

      Something close to this..
      Feel free to contact me via email, I'm glad to help! 🙂

      Good luck and regards,
      Felipe

    1. Hello Erik,

      I don’t think so. But I recommend you to take a look at my other post about plotting charts using ZedGraph.
      It’s a more powerful tool, you can save the chart as jpg as well. I’m just not sure about the pdf. But once you have the jpg only thing you got to do is convert it.

      Here is the link to my post:

      Plotting graphs in C# with ZedGraph and VS 2010

      Regards,
      Felipe

    1. Look, I found this at msdn

      “By default, the Chart control automatically sets the scale of the axes in chart areas based on its data series. You can manually set the Minimum, Maximum, Interval, IntervalOffset, IntervalType, and IntervalOffsetType properties for each axis. You can further customize them by defining different settings for an axis’s MajorGrid, MinorGrid, MajorTickMark, MinorTickMark, and LabelStyle properties. If you set the same property in the axis and in one of its components (for example, the Minimum property in both AxisY and AxisY.MajorGrid), the component setting takes precedence.

      When Axis.Interval is set to Auto, the Axis.IntervalAutoMode property determines how many intervals should be calculated. If your chart is resized or redrawn often at run time, you can set the Axis.IntervalAutoMode property to VariableCount. This way, the chart dynamically calculates axis intervals. This is useful if the chart intervals are displayed differently depending on the data.

      You can also use a logarithmic scale by setting the Axis.IsLogarithmic property to true.”

      Probably it should be something like
      chart1.ChartAreas[n].AxisX.Maximum
      chart1.ChartAreas[n].AxisY.Maximum

      Hope it helps
      Regards,
      Felipe

    2. This did the tric for me:
      ZedGraphControl zgc = new ZedGraphControl();
      GraphPane myPane = zgc.GraphPane;
      myPane.YAxis.Scale.Min = 0;
      myPane.YAxis.Scale.Max = 160;

      1. Yeah, ZedGraph is really cool.
        I’m sorry, I thought you were talking about MSChart.
        But I’m glad it worked.

        Regards,
        Felipe

  11. hye fpgentil, may i know how to do a chart in visual studio 2010 based on our input file data1, input file data2, and output . which mean 3series of chart in the same form.h. can u kindly reply me through emel or here. it is for my final year project. really appreaciate your help.
    liyana90@gmail.com

    1. Hello liyana,

      Well, all you have to do is Add 3 Series in the same Microsoft.Chart component and then set up each one to its related input file.

      If you have any problem with that, could you please show me your code ? You could use http://pastebin.com/

      Good luck.
      Regards,
      Felipe

    1. Hello,

      I’ve seen at Stack Overflow that you could solve your problem, am I right? If not, tell me and I’ll try to help you.

      Your code seems to be fine to me.

      Regards,
      Felipe

  12. hii i really liked the aricle can uhelp me can u tell me how to plot the graph exatcly the way u displayed in the first image
    thanx

    1. Hi Ketan,

      Do you mean the same function that I’ve used? If so, I’m sorry because I don’t have it anymore.
      Otherwise if you mean to plot more than one line per time only thing you have to do is setup 3 Series and its own values.

      Regards,
      Felipe

  13. can you tell me how a line in c# graphic that i give him 4 point in text boxes and it draw a line in panel

    1. Hello Afzaal,

      I’m sorry but I didn’t understand your question properly.
      Can you explain me what exactly are you trying to do?

      Regards,
      Felipe

      1. i say that how i draw a line what user give input point and and the draw mathmetical line as we say pevior point or line in visual grafic

  14. Hello fpgentil,

    I am getting serial data from serial port is there any way to plot graph for that using C#

    1. Hello yasaswi,
      Are you receiving data from serial port and storing them where?
      All you have to do is “save” your data in a list variable and follow the tutorial.
      It’s pretty simple. Good luck.

      Regards,
      Felipe

  15. hai,may i know how to do a chart in visual studio 2010 based on our two test results value,that we need to draw performance compaision graph of two algorithams.can u kindly reply me through email or here. it is for my final year project. really appreaciate your help

    1. Hello ranjana,

      I’d love to help but I need a couple of more informations. What kind of chart are you planning to draw? Line chart? Have you succeeded with my tutorial? Because it’s pretty simple, all you have to do is store your data into a list variable and setup the chart like I did.

      Regards,
      Felipe

  16. Hi, I am trying to follow your example but when running the code, it keeps giving me this
    Error 1 The name ‘SeriesChartType’ does not exist. Can you please give me your email so we can discuss my difficulties? Thanks.

  17. hello,
    Now your coord on the X axis is from 0 to10, if i want to be order descendent like 10 to 0, how i can this modify, ?

    1. Hello ionut,

      Have you tried to add in your chart1.Series[“test1”].Points.AddXY() your points decreasing from 10 to 0?

      Like
      for (i = 10, i > 0, i–)
      {
      chart1.Series[“test1”].Points.AddXY(i, rdn);
      }

      Hope it helps! Let me know if it still doesn’t work.

      Regards,
      Felipe

  18. Again me,

    I have another question, if i want to make the zoom on the grafic, or to put a scrool bar on the X ases, what is my posibility or how i can do this??
    thanks

  19. thanks for reply,yes i used the zedGraph at the first time, but with the zedgraph i havent be able to display the inverted data, like i ask you in the first post. if you know a solution for this with zedgraph will be great..all my problem will be resolved.

  20. =======================================================================
    Namespace/Enum Error: The name ‘SeriesChartType’ does not exist in the current context
    =======================================================================

    I got the above error many times, and I finally fixed it. Not sure which step worked, but here’s what I did:

    I have Visual Express 2010. Downloaded MSChart.exe from:
    http://www.microsoft.com/en-us/download/details.aspx?id=14422
    If you have 2008, see
    http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23903

    In the menu bar, click Project–>Add Reference–>System.Windows.Forms.DataVisualization–>OK

    Type the following in the top:
    using System.Windows.Forms.DataVisualization.Charting;

  21. Hi Felipe!

    Thank you for this post, really helped me a lot!
    I have a few questions though about implementing this code. Is it possible if we could maybe discuss it over email or gtalk? I am trying to plot incoming data from a serial port as a function of time, but I’m struggling a bit.

    Regards
    Trinette

    1. Hello Summy,

      Well, by default I actually haven’t done anything.
      But you could try to name your label with:
      Chart1.Series[“_SeriesName”].LegendText = “Name here!”

      Hope it helps!
      Regards,
      Felipe

  22. Hi Felipe,

    You’ve been such a great help so far to everyone.
    I really appreciate your great work and help.

    I have one issue with whom I am struggling and not sure what the cause is.
    I am using .Net framework 4.0 and trying to use chart on visual c# web form.

    I have used arraylist to store all the information for datasource but it did not show me the chart at all. Then thought to use the above code which you have posted in tutorial but again it did not work for me. I am not sure what is causing me this issue. I have checked temp folder security settings which is fine. I have created new solution with new chart again it did not work for me.
    I have added the namespace using System.Web.UI.DataVisualization.Charting;

    It would be really great if you could help me with this.

    Thanks in advance.
    Cheers!!

    1. Hello Ratika,

      Thank you so much for those words, it motivates me 🙂
      Well, I’m sorry that I took so long to answer, I’ve been really busy at work.

      So let’s go with your doubt now…
      Well, your code should be fine for me, I can’t tell whats wrong without looking at it.
      If you want to, you can add me at skype or simply mail me.

      Have you seen a library called ZedGraph? I wrote a tutorial as well, take a look.
      You could try a different way to plot your data, personally I prefer ZedGraph over MSChart because of its own features.

      Plotting graphs in C# with ZedGraph and VS 2010

      Good luck and best regards,
      Felipe

    1. Hello,

      Well, all you need is to setup your variables, in this case, global temperature and then plot it.
      Are you plotting a graph TEMPERATURE x TIME? The plot shouldn’t be difficult to implement.

      Anything I can help please let me know 🙂
      Regards,
      Felipe

  23. HI !! My name is Jack !! I had a project to build and I really wanna thank you cauz without this tutorials !!! I wound’nt never finished the project !! thanks a lot man

    1. Hello Eason,

      Which database are you using?
      Basically all you have to do is import your data into an array and then set its series like I did in this tutorial.

      Regards,
      Felipe

  24. I’m using mysql and i’m not sure how its import the data from database into an array by using for loop and pass it to the graph. Could you provide me an example code? I would be really appreciate if you could help me with this.

    Regards,
    Eason

  25. hi… using zigbee protocol m receiving vibration details( x and y axis ), now how can plot a graph using these details,graph looks should changed be dynamically ..

  26. Hmm so its not visual basic? tried the code and it complained all over the place till changed it to visual basic type coding ( ie for/next loops etc) hope the series and charts work out tho. Wish theyd make up their mind how to code . studio includes so many different kinds of code how do you keep it straight?

    1. Actually it’s C# and not VB.
      But it shouldn’t be so different in visual basic, have you tried replace the methods from their correspondent in vb? I believe it should work.

      Regards,
      Felipe

  27. Amazingly simple! Been breaking my head over it since quite some hours and the forums online haven’t been of much help…thanks a lot! 🙂 Also, how do I name the axes?

  28. Also, is there a way to stop the graph scale from reducing as the values keep increasing? LIke, can the scales according to which the graph has been plotted, be kept a constant and scrolling be enabled to view the previous data on the graph?

    1. I don’t think so, MSChart is a very limited component.
      That’s why I wrote a tutorial about ZedGraph, I totally recommend you to take a look.

      Regards,
      Felipe

    1. Hello j.vinoth,

      Basically you must store your data into a list and then plot following the tutorial the same way I did.

      Hope it helps.

      Regards,
      Felipe

  29. Hi Fpgentil,
    i am using MSChart to drawing a graph. the graph consists of the following things. X-axis is time and Y-axis is Throughput. the parallel to yaxis is a some state: a,b,c. i am having a problem to plotting a parallel state’s value along y-axis.

    my skype id is: muddsair.sharif

    i am waiting to hear from you.

    Regards

  30. hello FPGENTLI i ve just consulted your forum and I am facing some problems regarding SeriesChartType.Fastline its giving me some errors can you help please, my error window says SERIESCHARTTYPE doesnot exist, actually i have to draw the vlaues stored in an array in the form of a chart, its a part of my project i humble request you to help me please.

  31. wow its so beautifully explained… can you do a tutorial on how to update the underlying dataset if the user changes the curves by mouse dragging?

    1. Hello Najeeb,

      Thank you so much for your feedback.
      When you say ‘user changes the curves by mouse dragging’, do you mean click on the line and change the curve based on mouse position?

      If so, I’ll work on it.

      Best regards,
      Felipe

  32. If I want to pass co-ordiantes different for x and y how would I do that?? and how can I change the scale. The numbers showing on x and y axis …

    1. Hello Bilal,

      What exactly do you mean by pass different co-ordinates for X and Y? Are you talking about 2 different series? I didn’t get your question.

      I’m not sure if you’re able to change the scale. Have you seen my other post about another way to plot using C#?

      There’s a component called ZedGraph and it does pretty much all the job.

      Plotting graphs in C# with ZedGraph and VS 2010

      Regards,
      Felipe

    2. To change the scale, you can alter the max and min values on the x-axis.

      Try (for example):

      myChart.ChartAreas[0].AxisX.Maximum = 50;
      myChart.ChartAreas[0].AxisX.Minimum = 0;

  33. Thank You for the tutorial. I’ve never drawn a graph in VS2010 before, but I’m working on an app that would benefit from a graph – this looks like a good way to do it. Thanks again.

  34. my teacher gave me a project of making windows phone app ‘ Function Plotter ‘ Can you please help me in this case i even dont know how and where to start 😥
    i ll be very thankful

    1. Hello Ramsha,

      Actually I’m not a Windows Phone developer, although I believe it won’t be that different from C#. If I could help with .NET code, feel free to email me or add me on Skype.

      Regards,
      Felipe

  35. what if u wanted to enter one point at one press of a button, i tried it but it just keeps overwriting the previous point. i want it to add another XY coord

  36. Hello,
    With your exemple I suppose that the chart need a series of integers to work correctly right ?
    Can i use a series of custom object ?

    Thank.

    1. Hello Morgan,

      Well, I believe it works not only with integer numbers, double and float should work as well. Let me know if you have problems with that.

      Regards,
      Felipe

    1. Hello Iqra,

      Could you be a little bit more specific? If you simply want to plot longitude and latitude, couldn’t this be just like X and Y?

      Regards,
      Felipe

  37. hey, how do you combine a point graph and a line graph together? Like connecting one point to another point using lines? please reply me asap THANKS!!!

    1. Hello ABC,

      I believe even for linear equations you must add point by point. Perhaps Zedgraph has a better solution, have you seen my other post about plotting?

      Cheers,
      Felipe

  38. hello fgpentill

    Could you help me how to plot graph from modbus and plot it in time domain like this

    y= data from modbus
    x= time

    thx

  39. Hi,
    Please help me, error The name ‘SeriesChartType’ does not exist in the current context
    I’m using Visual C# 2010 Express
    Thank you.

  40. Hi Felipe. I need to connect two points. For example: pointA[0,0] and pointB[5,10]. How can I do that in chart please? Thank you.

    1. Hello Shah,

      Well, since this is a C# code, I don’t think you’ll be able to compile and run using Visual C++, you need Visual C# Express.

      Cheers,
      Felipe

  41. hi i have managed to draw a graph with a single Y-axis, now i need 3 y axes on the same graph. each will have a different scale, can you help with that? VS2010.

    1. Well, that depends on what language you’re talking about 😛
      Olá amigos is portuguese (I forgot the accent :/) and Hola amigos spanish! Thanks for the commend though \o/

Leave a reply to fpgentil Cancel reply