最近使用C#開發圖表,比較了DirectorChart,DontNetCharting,TeeChart,最終選用微軟的mschart開發,對於X軸作為時間軸探索了好久,終於實現了想要的效果。
界面效果:
核心源碼
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; using System.Windows.Forms.DataVisualization.Charting; namespace Krypton440Test { public partial class Form4 : ComponentFactory.Krypton.Toolkit.KryptonForm { public Form4() { InitializeComponent(); } private void Form4_Load(object sender, EventArgs e) { //清空原來數據緩存 chart1.Series[0].Points.Clear(); //定義圖表大小尺寸 chart1.Width = Width - 100; chart1.Height = Height - 100; //定義X軸、Y軸數據 double[] Ydata = { 20, 3, 23 ,6}; DateTime[] Xdate = new DateTime[] { DateTime.Parse("09:10:02"), DateTime.Parse("09:10:10"),DateTime.Parse("09:10:15"), DateTime.Parse("09:10:20") }; //以下按照先繪制chartArea、然后再繪制Series的步驟畫圖 //chartArea背景顏色 chart1.BackColor = Color.Azure; //X軸設置 chart1.ChartAreas[0].AxisX.Title = "時間"; chart1.ChartAreas[0].AxisX.TitleAlignment = StringAlignment.Near; chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;//不顯示豎着的分割線 /************************************************************************/ /* 本文重點講解時間格式的設置 * 如果想顯示原點第一個時間坐標,需要設置最小時間,時間間隔類型,時間間隔值等三個參數*/ /************************************************************************/ chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss"; //X軸顯示的時間格式,HH為大寫時是24小時制,hh小寫時是12小時制 chart1.ChartAreas[0].AxisX.Minimum = DateTime.Parse("09:10:02").ToOADate(); chart1.ChartAreas[0].AxisX.Maximum = DateTime.Parse("09:10:21").ToOADate(); chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Seconds;//如果是時間類型的數據,間隔方式可以是秒、分、時 chart1.ChartAreas[0].AxisX.Interval = DateTime.Parse("00:00:02").Second;//間隔為2秒 //Y軸設置 chart1.ChartAreas[0].AxisY.Title = "數據點"; chart1.ChartAreas[0].AxisY.TitleAlignment = StringAlignment.Center; chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = true;//顯示橫着的分割線 chart1.ChartAreas[0].AxisY.Minimum = 0; chart1.ChartAreas[0].AxisY.Maximum = 25; chart1.ChartAreas[0].AxisY.Interval = 5; //Series繪制 chart1.Series[0].LegendText = "溫度點"; chart1.Series[0].ChartType = SeriesChartType.Spline; chart1.Series[0].XValueType = ChartValueType.DateTime; chart1.Series[0].IsValueShownAsLabel = true;//顯示數據點的值 chart1.Series[0].MarkerStyle = MarkerStyle.Circle; //把數據點添加到Series圖表中 for (int i = 0; i < Xdate.Length; i++) { chart1.Series[0].Points.AddXY(Xdate[i], Ydata[i]); } } } }