2012/08/24

C#.Net使用zedgraph套件做曲線圖

最近想做一隻簡單的程式,不過想說要怎麼畫曲線圖等等的…
上網狗了一下找到了這篇,[C#] - 使用zedgraph做圓餅圖

不過只有介紹怎麼用套件去做出東西,看了還有點不懂,所以我自己來寫一個筆記
參考了一下這篇,.NET控件ZedGraph使用帮助,比較詳細介紹出套件使用方法

先去ZedGraph將套件下載下來,在下載的目錄有幾個比較重要的分別是zedgraph sourcezedgraph dll onlyzedgraph documentation




其我們今天要使用的是zedgraph dll only
請先將5.1.5的版本下載下來,下載下來後將其解壓縮,內容會如下圖一樣



開啟VS並選到 /工具/選擇工具箱選項 ,並按下瀏覽將剛剛的ZedGraph.dll加入到工具箱,使用Web的朋友們就將ZedGraph.Web.dll加入近來




接著會在工具箱的所有Windows Form裡面看到ZedGraphControl這個小工具



把他拖曳到視窗上,就會出現如下圖的畫面


今天所使用的Code是A flexible charting library for .NET所提供的範例程式碼,程式碼如下:

// Respond to the form 'Resize' event
private void Form1_Resize( object sender, EventArgs e )
{
   SetSize();
}

// SetSize() is separate from Resize() so we can 
// call it independently from the Form1_Load() method
// This leaves a 10 px margin around the outside of the control
// Customize this to fit your needs
private void SetSize()
{
   zedGraphControl1.Location = new Point( 10, 10 );
   // Leave a small margin around the outside of the control
   zedGraphControl1.Size = new Size( ClientRectangle.Width - 20,
                           ClientRectangle.Height - 20 );
}

// Respond to form 'Load' event
private void Form1_Load( object sender, EventArgs e )
{
   // Setup the graph
   CreateGraph( zedGraphControl1 );
   // Size the control to fill the form with a margin
   SetSize();
}

// Build the Chart
private void CreateGraph( ZedGraphControl zgc )
{
   // get a reference to the GraphPane
   GraphPane myPane = zgc.GraphPane;

   // Set the Titles
   myPane.Title.Text = "My Test Graph\n(For CodeProject Sample)";
   myPane.XAxis.Title.Text = "My X Axis";
   myPane.YAxis.Title.Text = "My Y Axis";

   // Make up some data arrays based on the Sine function
   double x, y1, y2;
   PointPairList list1 = new PointPairList();
   PointPairList list2 = new PointPairList();
   for ( int i = 0; i < 36; i++ )
   {
      x = (double)i + 5;
      y1 = 1.5 + Math.Sin( (double)i * 0.2 );
      y2 = 3.0 * ( 1.5 + Math.Sin( (double)i * 0.2 ) );
      list1.Add( x, y1 );
      list2.Add( x, y2 );
   }

   // Generate a red curve with diamond
   // symbols, and "Porsche" in the legend
   LineItem myCurve = myPane.AddCurve( "Porsche",
         list1, Color.Red, SymbolType.Diamond );

   // Generate a blue curve with circle
   // symbols, and "Piper" in the legend
   LineItem myCurve2 = myPane.AddCurve( "Piper",
         list2, Color.Blue, SymbolType.Circle );

   // Tell ZedGraph to refigure the
   // axes since the data have changed
   zgc.AxisChange();
}

執行後成果如下圖


要使用這個套件的人,建議將dll放置在自訂資料夾,要使用這套可以搭配zedgraph documentation一起使用



參考文章:
http://www.codeproject.com/Articles/5431/A-flexible-charting-library-for-NET
http://yanchi-huang.blogspot.tw/2010/04/zedgraph-pie-chart.html
http://www.cnblogs.com/ynyhn/articles/504023.html
http://www.dotblogs.com.tw/yanchi/archive/2010/12/16/20175.aspx