MSChart使用总结
- 格式:docx
- 大小:845.48 KB
- 文档页数:13
MSChart控件series属性的看法和心得1.Annotations --图形注解集合2.ChartAreas --图表区域集合3.Legends --图例集合4.Series --图表序列集合(相当于层次,同一个area中不同series相当于不同层次的关系,也可以理解为不同对象的关系,后面细说)5.Titles --图标的标题集合MSChart是微软在.NET3.5下开发出来的免费图标控件,在VS2008以上版本才能使用。
MSDN上面虽然能下载WinSamples,但是对于初学者来说,MSChart还是有难度的,如果没有人指点的话,那是很费时间的;而demo里面都是些相对复杂的例子,比如要实现两个ChartAreas的series重叠起来通过手动切换柱状图和饼状图这个效果就让我纠结了好久。
研究了很久,特别是在柱状图显示不同颜色的地方,如果对于series没有参透明白的话真的相当麻烦。
要实现同一个series里不同颜色仅需设置series.palette属性即可,上图中属性值为BrightPastel而要实现两个图标在同一个位置切换,在设计时,可调整chartarea的position属性,实现两个图标重叠总结:series——可以把它想象成是一个透明的箱子但是这个箱子只能装同一种类型的东西装了衣服就不能装裤子了说是透明箱子是因为考虑到chart工具的特性,无伤大雅如果你要比较衣服和裤子的数量就需要两个箱子(series)而要比较每条裤子的不同就只需要一个箱子(series)就可以了每条裤子就是一个point,设置好series里的point就可以了,不过饼状图由于是圆形的,所以只用设置point的Y轴数据就可以了。
一.数据源说到绘制图表,可能很多人的第一反应除了是图表呈现的方式外,更关心的便是数据如何添加,记得在很多年前,哪时要绘制一个数据曲线图,一直找不到好的呈现方式,后来使用了SVG的绘图模式,不过在添加数据的时候可谓吃尽了苦头,毕竟,SVG只是一种描述语言,要动态的实现一个图表的绘制,是非常困难的.对于微软的图表控件,数据添加是一件很简单的方式,它支持多种数据添加方式,如:·可以在图表的设计界面,在属性设置窗口中的Series属性下的Points中添加需要的数据.·可以在图表的设计界面中,在属性中绑定一个数据源.·可以在后台代码中,动态添加数据.·可以在后台代码中设置一个或多个数据源,直接绑定到图表中.在此处,我只着重讲解一下第3,4两点.对于第3点,相对来说比较简单,在后台代码中,找到要添加代码的Series,通过它下面Points的Add、AddXY、AddY等方法,即可以实现数据的添加.例如:1. double t;2. for(t = 0; t <= (2.5 * Math.PI); t += Math.PI/6)3. {4. double ch1 = Math.Sin(t);5. double ch2 = Math.Sin(t-Math.PI/2);6. Chart1.Series["Channel 1"].Points.AddXY(t, ch1);7. Chart1.Series["Channel 2"].Points.AddXY(t, ch2);8. }复制代码注:代码摘自微软的例子,上例中,Chart1为图表的名字,Channel 1、Channel 2分别表示两个Series数据序列)二.绑定数据先来看看图表控件都支持什么类型的数据绑定,根据官方文档的说法,只要是实现了IEnumerable接口的数据类型,都可以绑定到图表控件中,例如:DataView, DataReader, DataSet, DataRow, DataColumn, Array, List, SqlCommand, OleDbCommand, SqlDataAdapter, 及OleDbDataAdapter对象。
c# ms chart 控件使用方法第一个简单的chart:创建曲线图chart1.Series.Clear();Series series = new Series("Spline");series.ChartType = SeriesChartType.Spline;series.BorderWidth = 3;series.ShadowOffset = 2;// Populate new series with dataseries.Points.AddY(67);series.Points.AddY(57);series.Points.AddY(83);series.Points.AddY(23);series.Points.AddY(70);series.Points.AddY(60);series.Points.AddY(90);series.Points.AddY(20);// Add series into the chart's series collectionchart1.Series.Add(series);同时显示2条曲线// Populate series with random dataRandom random = new Random();for (int pointIndex = 0; pointIndex < 10;pointIndex++){Chart1.Series["Series1"].Points.AddY(random.Next(45, 95)); Chart1.Series["Series2"].Points.AddY(random.Next(5, 75)); }// Set series chart typeChart1.Series["Series1"].ChartType = SeriesChartType.Line; Chart1.Series["Series2"].ChartType = SeriesChartType.Spline;// Set point labelsChart1.Series["Series1"].IsValueShownAsLabel = true;Chart1.Series["Series2"].IsValueShownAsLabel = true;// Enable X axis marginChart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;// Enable 3D, and show data point marker linesChart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; Chart1.Series["Series1"]["ShowMarkerLines"] = "True";Chart1.Series["Series2"]["ShowMarkerLines"] = "True";显示column类型图,柱状图// Create new data series and set it's visual attributesChart1.Series.Clear();Series series = new Series("FlowRead");series.ChartType = SeriesChartType.Column;series.BorderWidth = 3;series.ShadowOffset = 2;// Populate new series with dataseries.Points.AddY(67);series.Points.AddY(57);series.Points.AddY(83);series.Points.AddY(23);series.Points.AddY(70);series.Points.AddY(60);series.Points.AddY(90);series.Points.AddY(20);// Add series into the chart's series collectionChart1.Series.Add(series);很多点,效率还可以// Fill series datadouble yValue = 50.0;Random random = new Random();for (int pointIndex = 0; pointIndex < 20000;pointIndex++){yValue = yValue + (random.NextDouble() * 10.0 - 5.0);Chart1.Series["Series1"].Points.AddY(yValue);}// Set fast line chart typeChart1.Series["Series1"].ChartType = SeriesChartType.FastLine;日期,xy类型// Create a new random number generatorRandom rnd = new Random();// Data points X value is using current date DateTime date = DateTime.Now.Date;// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY( date, // X value is a daternd.Next(40,50)); //Close Y value// Add 1 day to our X valuedate = date.AddDays(1);int-int的xy数据绘图// Create a new random number generatorRandom rnd = new Random();// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY(rnd.Next(10,90), // X value is a date rnd.Next(40,50)); //Close Y value数据库数据,datetime-int类型Chart1.Series.Clear();OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 时间,序号from pub_log_read order by 序号asc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.DataBindTable(dr, "时间");dr.Close();数据库数据2,string-int类型Chart1.Series.Clear();OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号asc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.DataBindTable(dr, "账号");dr.Close();数据库绑定3-string-int型Chart1.Series.Clear();Chart1.Series.Add("Series1");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号asc";conn.Open();DataSet ds = new DataSet();OleDbDataAdapter da = new OleDbDataAdapter();da.SelectCommand = cmd;da.Fill(ds, "tbscore");Chart1.DataSource = ds;Chart1.Series["Series1"].XValueMember = "账号";Chart1.Series["Series1"].YValueMembers = "次数";// Data bind to the selected data sourceChart1.DataBind();conn.Close();数据库4,只绑定yChart1.Series.Clear();Chart1.Series.Add("序号");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 序号from pub_log_read order by 序号asc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series[0].Points.DataBindY(dr);dr.Close();数据库5,绑定xyChart1.Series.Clear();Chart1.Series.Add("序号");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号desc";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series[0].Points.DataBindXY(dr,"账号",dr,"次数");dr.Close();数据库6,支持显示参数Chart1.Series.Clear();Chart1.Series.Add("S1");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "SELECT * FROM REPSALES WHERE Year=2004";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.Series[0].Points.DataBind(dr, "name", "sales", "Tooltip=Year,Label=Commissions{C2}");dr.Close();数据库7,支持多lineChart1.Series.Clear();Chart1.Series.Add("S1");OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");OleDbCommand cmd = conn.CreateCommand();conn.Open();mandText = "SELECT * FROM REPSALES";//DataSet ds = new DataSet();//OleDbDataAdapter da = new OleDbDataAdapter();//da.SelectCommand = cmd;//da.Fill(ds, "tbscore");OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);Chart1.DataBindCrossTable(dr, "Name", "Year", "Sales", "Label=Commissions{C}");dr.Close();数据库8,按照行添加数据// Resolve the address to the Access databasestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\chartdata.mdb";//Initialize a connectionstringstringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;// Definethe databasequerystringmySelectQuery="SELECT * FROM SALESCOUNTS;";// Createa database connection object using the connectionstringOleDbConnection myConnection = newOleDbConnection(myConnectionString);// Create adatabase command on the connection usingqueryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Open theconnectionmyCommand.Connection.Open();//Initializes a new instance of the OleDbDataAdapter classOleDbDataAdapter myDataAdapter = new OleDbDataAdapter();myDataAdapter.SelectCommand = myCommand;//Initializes a new instance of the DataSet classDataSetmyDataSet = new DataSet();// Addsrows in the DataSetmyDataAdapter.Fill(myDataSet,"Query");foreach(DataRow row in myDataSet.Tables["Query"].Rows){// For each Row add a new seriesstring seriesName = row["SalesRep"].ToString();Chart1.Series.Add(seriesName);Chart1.Series[seriesName].ChartType = SeriesChartType.Line;Chart1.Series[seriesName].BorderWidth = 2;for(int colIndex = 1; colIndex <myDataSet.Tables["Query"].Columns.Count; colIndex++) {// For each column (column 1 and onward) add the value as apointstring columnName =myDataSet.Tables["Query"].Columns[colIndex].ColumnName; int YVal = (int) row[columnName];Chart1.Series[seriesName].Points.AddXY(columnName, YVal);}}DataGrid.DataSource = myDataSet;DataGrid.DataBind();// Closesthe connection to the data source. This is the preferred// method ofclosing any open connection.myCommand.Connection.Close();使用xml数据// resolve the address to the XML documentstringfileNameString = this.MapPath(".");stringfileNameSchema = this.MapPath(".");fileNameString += "..\\..\\..\\data\\data.xml";fileNameSchema += "..\\..\\..\\data\\data.xsd";//Initializes a new instance of the DataSet classDataSetcustDS = new DataSet();// Read XMLschema into the DataSet.custDS.ReadXmlSchema( fileNameSchema );// ReadXML schema and data into the DataSet.custDS.ReadXml( fileNameString );//Initializes a new instance of the DataView classDataViewfirstView = new DataView(custDS.Tables[0]);// Sincethe DataView implements and IEnumerable, pass the reader directlyinto// theDataBindTable method with the name of the column used for the Xvalue.Chart1.DataBindTable(firstView, "Name");使用excel数据// resolve the address to the Excel filestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\ExcelData.xls";// Createconnection object by using the preceding connection string.string sConn= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +fileNameString + ";Extended Properties="Excel8.0;HDR=YES"";OleDbConnection myConnection = new OleDbConnection( sConn );myConnection.Open();// Thecode to follow uses a SQL SELECT command to display the data fromthe worksheet.// Createnew OleDbCommand to return data from worksheet.OleDbCommandmyCommand = new OleDbCommand( "Select * From[data1$A1:E25]",myConnection );// createa databasereaderOleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);//Populate the chart with data in the fileChart1.DataBindTable(myReader, "HOUR");// closethe reader and the connectionmyReader.Close();myConnection.Close();使用csv数据// Filename of the CSV filestring file= "DataFile.csv";// Getthe path of the CSV filestring path= this.MapPath(".");path +="..\\..\\..\\data\";// Createa select statement and a connection string.stringmySelectQuery = "Select * from " + file;stringConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+path+ ";Extended Properties="Text;HDR=No;FMT=Delimited"";OleDbConnection myConnection = new OleDbConnection(ConStr);// Createa database command on the connection using queryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Openthe connection and create the readermyCommand.Connection.Open();OleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);// Column1 is a time value, column 2 is a double// Databindthe reader to the chart using the DataBindXY methodChart1.Series[0].Points.DataBindXY(myReader, "1", myReader,"2");// Closeconnection and data readermyReader.Close();myConnection.Close();数组绘图// Initialize an array of doublesdouble[] yval = { 2, 6, 4, 5, 3 };// Initialize an array of stringsstring[] xval = { "Peter", "Andrew", "Julie", "Mary", "Dave" };// Bind the double array to the Y axis points of the Default dataseriesChart1.Series["Series1"].Points.DataBindXY(xval, yval);数据库9,dataview// Resolve the address to the Access databasestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\chartdata.mdb";//Initialize a connectionstringstringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;// Definethe databasequerystringmySelectQuery="SELECT * FROM REPS;";// Createa database connection object using the connectionstringOleDbConnection myConnection = newOleDbConnection(myConnectionString);// Create adatabase command on the connection usingqueryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Open theconnectionmyCommand.Connection.Open();//Initializes a new instance of the OleDbDataAdapter classOleDbDataAdapter custDA = new OleDbDataAdapter();custDA.SelectCommand = myCommand;//Initializes a new instance of the DataSet classDataSetcustDS = new DataSet();// Addsrows in the DataSetcustDA.Fill(custDS, "Customers");//Initializes a new instance of the DataView classDataViewfirstView = new DataView(custDS.Tables[0]);// Sincethe DataView implements IEnumerable, pass the dataview directlyinto// the DataBind method with thename of the Columns selected in thequeryChart1.Series["Default"].Points.DataBindXY(firstView,"Name",firstView, "Sales");// Closesthe connection to the data source. This is the preferred// method of closing any openconnection.myCommand.Connection.Close();指定坐标轴的数据显示范围// Create a new random number generatorRandom rnd = new Random();// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY(rnd.Next(10,90), // X value is a daternd.Next(40,50)); //Close Y value}Chart1.ChartAreas[0].AxisY.Minimum = 40;Chart1.ChartAreas[0].AxisY.Maximum = 50;数据排序// Use point index for drawing the chartChart1.Series["Series1"].IsXValueIndexed = true;// Sortseries points by second Y valueChart1.DataManipulator.Sort(PointSortOrder.Ascending, "Y2","Series1");查找数据最大值和最小值// Find point with maximum Y value and change colorDataPointmaxValuePoint =Chart1.Series["Series1"].Points.FindMaxValue(); maxValuePoint.Color = Color.FromArgb(255, 128, 128);// Findpoint with minimum Y value and change colorDataPointminValuePoint =Chart1.Series["Series1"].Points.FindMinValue(); minValuePoint.Color = Color.FromArgb(128, 128, 255);pie显示交互private void Page_Load(object sender, System.EventArgs e){// Addseries to the chartSeriesseries = Chart1.Series.Add("My series");// Setseries and legend tooltipsseries.ToolTip = "#VALX: #VAL{C} million";series.LegendToolTip = "#PERCENT";series.PostBackValue = "#INDEX";series.LegendPostBackValue = "#INDEX";// Populateseries datadouble[] yValues = {65.62, 75.54, 60.45, 34.73, 85.42, 32.12, 55.18, 67.15,56.24, 23.65};string[] xValues = {"France", "Canada", "Germany", "USA", "Italy", "Russia","China", "Japan", "Sweden", "Spain" };series.Points.DataBindXY(xValues, yValues);// Setseries visual attributesseries.Type= SeriesChartType.Pie;series.ShadowOffset = 2;series.BorderColor = Color.DarkGray;series.CustomAttributes = "LabelStyle=Outside";}protected void Chart1_Click(object sender, ImageMapEventArgse){intpointIndex = int.Parse(e.PostBackValue);Seriesseries = Chart1.Series["My series"];if(pointIndex >= 0 &&pointIndex < series.Points.Count){series.Points[pointIndex].CustomProperties +="Exploded=true";}}chart点击事件/// <summary>/// Page Load event handler./// </summary>protected void Page_Load(object sender, System.EventArgs e){this.Chart1.Click += new ImageMapEventHandler(Chart1_Click);// directusing of PostBackValueforeach(Series series in this.Chart1.Series){series.PostBackValue = "series:" + + ",#INDEX";}// transferof click coordinates. getCoordinates is a javascriptfunction.stringpostbackScript =ClientScript.GetPostBackEventReference(this.Chart1,"chart:@");this.Chart1.Attributes["onclick"] = postbackScript.Replace("@'", "'+ getCoordinates(event)"); }/// <summary>/// Handles the Click event of the Chart1 control./// </summary>/// <param name="sender">The sourceof the event.</param>/// <paramname="e">The<seecref="System.Web.UI.WebControls.ImageMapEventArgs"/>instance containing the eventdata.</param>protected void Chart1_Click(object sender, ImageMapEventArgse){this.Chart1.Titles["ClickedElement"].Text = "Nothing";string[]input = e.PostBackValue.Split(':');if(input.Length == 2){string[] seriesData = input[1].Split(',');if (input[0].Equals("series")){this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element:" + seriesData[0] + " - Data Point #" + seriesData[1];}else if (input[0].Equals("chart")){// hit test of X and Y click pointHitTestResult hitTestResult=this.Chart1.HitTest(Int32.Parse(seriesData[0]),Int32.Parse(seriesData[1]));if (hitTestResult != null){this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element:" + hitTestResult.ChartElementType.ToString();}}}}。
C# 中使用MSChart 组件
2013/03/17 0 这两天在研究怎样在C# 中使用MSChart 组件来绘制柱状、饼状图形,由于以前没有接触过MSChart 组件,关于这方面的资料也没有;于是就到
网上狂搜一把,找到了一些相关的资料,但资料都写的不完整;现在将自己摸索的
心得整理一下:
1、将MSChart control 的引用添加到工具栏。
选择“工具- 选择工具箱项”,然后切换到“COM组件”页,选择“Microsoft Chart Control 6.0 (OLEBD)”,点击确定后就可以成功加载控件了。
2、添加引用,using MSChart20Lib;
3、定义图表样式
//图表标题
MSChartBar.TitleText = 年度统计图表
//页底说明
MSChartBar.Footnote.Text = 说明:年度柱状统计图表
//设置图例
MSChartBar.ShowLegend = true;
MSChartBar.Legend.Location.LocationType = VtChLocationType.VtChLocationTypeRight;
//设置Plot 的Shadow
MSChartBar.Plot.Backdrop.Shadow.Style = VtShadowStyle.VtShadowStyleDrop; //设置Shadow 的大小
MSChartBar.Plot.Backdrop.Shadow.Offset.Set(60, 60);。
mschart安装使用最近需要为程序显示一些柱状图、线图之类的,查了一下微软的mschart不错,功能强大。
可是自vc6.0之后mschart控件就从ms的IDE里去掉了,如果用只能自己下载安装。
安装mschart需要1 .net framewrok 3.5 sp1(注意是sp1),没有安装的话就去下载吧,完整包大概200多M2 安装MSChart.exe MSChart_VisualStudioAddOn.exe 下载mschrt20.ocx 到C:\WINDOWS\system32目录下。
命令行运行regsvr32 mschrt20.ocx注册控件3 在vs2005之后的平台上,你要么在class view下add class->MFC Class f rom ActiveX Control然后有两个,你可以选择registy然后选择ms mschart 6.0(o led),这样只能出现一个类CMSCHART,或者选择File然后浏览mschrt20.ocx,这里面生成了很多类,你全部添加进去,最后就可以用了。
第二、你可以在一个MFC dialog上insert axtivex control或者toolbox选择choose item->com选择组件让它出现在工具箱中,这样也可以有控件。
我们自己选择生成的很多类,跟网上有示例的类函数名称上有所不同,可能会给使用带来麻烦。
其实最简单的就是找到一个Demo把里面相关的CMSCHART和其它相关的十几个类都拷贝到我的工程文件夹里,再添加进来,就ok了。
网上很多例子可供参考,比如:/document/viewdoc/?id=9 59关于遇到的一些问题。
在设置图形类型的时候,m_chart.SetChartType(1|2);显示出2D曲线图,而我们用m_chart.SetChartType(16);的时候如果你只设置了m_chart. SetColumnCount(1); 就不会显示,因为16的散列图需要的是一对坐标点,你至少需要设置m_chart.SetColumnCount(2);为2。
一、概述在数据可视化中,注释是一种重要的功能,它可以帮助用户更清晰地理解图表中的数据,传达更加准确和清晰的信息。
MSChart是微软公司提供的一种图表绘制工具,具有丰富的功能和灵活的应用方式。
本文将介绍MSChart中注释的使用方法,帮助读者更好地利用这一功能进行数据可视化和分析。
二、MSChart注释的基本概念1. MSChart是什么?MSChart是微软公司提供的一种用于绘制图表的工具,它能够生成丰富多样的图表,包括线形图、柱状图、饼图等。
MSChart提供了丰富的功能和参数,能够满足用户在数据可视化方面的需求。
2. 注释在数据可视化中的作用注释是指在图表中添加文字、箭头、线条等元素,用来对图表中某个特定的数据点或趋势进行解释和说明。
注释能够让用户更加直观地理解数据,传达更加有效和清晰的信息。
三、在MSChart中使用注释的方法1. 添加注释在MSChart中,用户可以通过以下步骤添加注释:(1)通过代码:在代码中使用Annotation类的实例来创建并添加注释。
(2)通过设计器:在设计器中选择需要添加注释的图表,右键点击选择“添加注释”,然后在图表上选择需要添加注释的位置,并输入注释内容。
2. 设置注释的样式和格式MSChart提供了丰富的接口和属性来设置注释的样式和格式,包括字体、颜色、格式、位置等。
用户可以根据自己的需求对注释进行定制化设置,使得注释更加符合实际应用场景和用户需求。
3. 对注释进行交互操作在MSChart中,用户可以对注释进行交互操作,包括拖动、调整大小、隐藏、显示等。
这种交互操作能够帮助用户更好地理解数据,并进行更深入的分析和研究。
4. 多种类型的注释除了常见的文字注释外,MSChart还支持添加箭头、线条等元素作为注释,这些不同类型的注释能够更好地帮助用户理解数据,传达更加清晰的信息。
四、注意事项和常见问题1. 注释的数量和位置在使用注释时,需要注意不要添加过多的注释,这会导致图表混乱,影响用户的观感。
代码<asp:Chart ID="Chart1" runat="server"><Series><asp:Series Name="Series1"></asp:Series></Series><ChartAreas><asp:ChartArea Name="ChartArea1"></asp:ChartArea></ChartAreas></asp:Chart>相信在你们看过微软的实例后对这些属性会有一些了解滴..然后进入正题,本文也主要介绍MSChart的折线图,圆饼图,和柱状图, 因为这三种本人感觉是最常用的.对于这三种用MSChart来实现的话本人感觉比较困难的就是数据绑定带来的麻烦,因为在我们平时使用的时候基本都是动态的数据,而微软实例基本都是写死在页面上的数据, 而且网上这方面资料也比较少,只能自己动手实践啦.先介绍几种MSChart的数据绑定方式,第一种,也是最通俗的一种Chart1.DataSource = GetData.GetChartData();Chart1.Series["ChartArea1"].XValueMember = "home";Chart1.Series["ChartArea1"].YValueMembers = "num1";第二种往后都是通过List的集合形式绑定数据,这里就用变量list来代替了.一些变量都是对应实体类的名称当然也对应数据库字段Chart1.DataBindTable(list, "home");"home"是x轴坐标第三种,home 分组,Time X轴坐标,num1 y轴坐标Chart1.DataBindCrossTable(list, "home", "Time", "num1", "Label=num1,ToolTip= num1");第三种,折线图绑定方式Chart1.Series[0].Points.DataBind(list, "home", "num1", "Label=num1,ToolTip=nu m1");第四种,折线图绑定方式代码Chart1.DataBindCrossTable(list, "home", "Time", "num1", "Label=num1,ToolTip= num1");//绘制线条MarkerStyle marker = MarkerStyle.Square;foreach (Series ser in Chart1.Series){ser.ShadowOffset = 1;ser.BorderWidth = 2;ser.ChartType = SeriesChartType.Line;ser.MarkerSize = 12;ser.MarkerStyle = marker;ser.MarkerBorderColor = Color.FromArgb(64, 64, 64);ser.Font = new Font("Trebuchet MS", 8, FontStyle.Regular);marker++;}第五种:Chart1.Series["Series1"].Points.DataBindXY(list, "home", list, "num1"); 我所了解的就这么几种了,有朋友知道有更好的绑定方式不妨贴上代码来.下面介绍下MSChart下的柱形图常用的属性这篇博客都有介绍,在这里我就不罗嗦了../wenjl520/archive/2009/05/16/1458461.html代码//是否启用3D显示Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;//显示类型,可以是柱形折线等等Chart1.Series[0].ChartType = SeriesChartType.Line;//// Draw as 3D CylinderChart1.Series[0]["DrawingStyle"] = "Cylinder";//像素点见宽度Chart1.Series[0]["PointWidth"] = "0.8";//是否显示数值Chart1.Series[0].IsValueShownAsLabel = true;//X轴数据显示间隔Chart1.ChartAreas[0].AxisX.Interval = 1;//直角坐标显示,Chart1.ChartAreas[0].Area3DStyle.IsRightAngleAxes = false;//是否群集在一起Chart1.ChartAreas[0].Area3DStyle.IsClustered = false;//转动X轴角度Chart1.ChartAreas[0].Area3DStyle.Inclination = 40;//转动Y轴角度Chart1.ChartAreas[0].Area3DStyle.Rotation = 20;foreach (Series ser in Chart1.Series){//柱形宽度ser["PixelPointWidth"] = "40";//像素点深度ser["PixelPointDepth"] = "80";//像素点间隙深度ser["PixelPointGapDepth"] = "10";}这些属性都是设置MSChart的外观样式的属性,大家可以尝试修改试试,当然主要的是绑定数据了.所以在调用这些属性时先用上文介绍的几种绑定方式绑定数据.有些属性可能在3D模式下失效或者在2D模式下失效,这是正常现象,效果图:折线图:属性同上..有些属性会在折线图下失效,效果图:圆饼图:代码IList<ChartModel> list = GetData.GetChartDataListByPie();//数值显示百分比形式Chart1.Series["Series1"].Label = "#PERCENT{P}";Chart1.Series["Series1"].Points.DataBind(list, "home", "num1", "Legend Text=home,YValues=num1,ToolTip=num1");Chart1.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Chart ing.SeriesChartType.Pie;Chart1.Series["Series1"].ToolTip = "#LEGENDTEXT: #VAL{C} million";Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;这个比较简单吧..主要是这里的 Chart1.Series["Series1"].Points.DataBind(list, "home", "num1", "LegendText=home,YValues=num1,ToolTip=num1");LegendText整了我半天.这个是显示右侧说明的,开始老是显示不出来,而且还不统一. Legend其实就是右侧显示的说明,但是做过的朋友会发现在柱形图还有折线图如果页面指定了一个<Lengend></Lengend>标签的话,会多显示一个,所以需要在执行绑定的时候写上这么一段代码 Chart1.Series.Clear();。
图表绘制控件mschart的使⽤⽅法1VisualBasic中ActiveX控件MSChart的使⽤⽅法*依⽪提哈尔·穆罕买提,那斯尔江·⼟尔逊(新疆⼤学数学与系统科学学院,乌鲁⽊齐,830046)热依曼·吐尔逊(新疆⼤学信息⼯程学院,乌鲁⽊齐,830046)摘要:本⽂⾸先介绍了VisualBasic(简称VB)中MSChart控件的使⽤⽅法,然后通过简单的例⼦详细介绍了利⽤MSChart控件绘制Excel数据源图表的⽅法。
关键词:VisualBasic;MSChart控件;MicrosoftExcel数据表;图表;数据库The Methods of Using MSChart Control Based on VBIptihar.Muhammat,Nasirjan.Tursun(Mathematics and Systematic Science Institude of XinjiangUniversity,Urumqi,Xinjiang,830046)Reyima.Tursun(Information Science and Engineering Institude of Xinjiang University,Urumqi,Xinjiang,830046)Abstract:This article discusses how to use the MSChart control and how that is used in the VB project to drawing Microsoft? Excel charts.KeyWords: MSChart Control;Chartdata ;Mirosoft Excel Sheets;Chart;Database1. 引⾔Visual Basic中的MSChart控件是⼀个功能强⼤的⾼级图表⼯具,拥有丰富的图表绘制功能,⽤它来可以显⽰⼆维和三维的棒图、区域图、线形图、饼图等多种常⽤图表。
1、MSChart控件的属性(1)ChartType属性:用于设置或返回图表类型,MSChart控件图表类型与对应ChartType属性值如表8.7所示。
如,ChartType=1则显示二维直方图,ChartType=14则显示饼图。
表8.7 MSChart图表类型(2)行(格)属性①RowCount属性:用于表示图表中总格(行)数。
例如:若MSChart控件显示二维数组Array_2(M,N),则总格(行)数RowCount=M。
如:RowCount=5,表示有5格(行)数据。
若MSChart控件显示一维数组Array_1(N)的元素值,则总行数RowCount=1。
②Row属性:用于表示图表中某格(行)的序号。
若MSChart控件显示二维数组Array_2(M,N),则图表中第I格的序号Row=I,当Row=1表示第1格(行)数据。
③RowLabel属性:用于表示格(行)标签名,默认值为Ri。
用户可以修改其值,如改为无锡地区人数、南京地区人数等。
④RowLabelCount属性:用于表示格(行)标签数,MSChart控件允许设置多个格(行)标签。
通常取值为1,当需要用2行以上的标签时,才修改此属性。
⑤RowLabelIndex属性:用于表示格(行)标签序号,用户通过设置不同格(行)标签序号选择不同格(行)标签进行编辑。
(3)列属性①ColumnCount属性:用于表示图表中每格(行)中的列数,即数组中列数N。
如设置ColumnCount=3,则每格(行)中有3列,图表每数据格用3个矩形或3个扇形表示。
②Column属性:用于表示图表中某格(行)某列的列序号,例如:Row=1,Column=1,表示图表中第1格(行)第1列。
③ColumnLabel属性:用于表示图表列标签名,默认为Ci。
④ColumnLabelCount属性:用于表示图表某格中的列标签数。
⑤ColumnLabelIndex属性:用于表示图表某格中的列标签序号。
目录一、MSChart控件的总体介绍图 (2)二、属性 (2)1.属性ChartAreas (2)2.属性ChartSeries (2)3.属性Legends (3)4.怎么设置图表中X轴和Y轴的区域 (3)5.如何启用图表的3D显示效果 (4)6.如何设置图表标题 (5)7.如何设置图表线的宽度 (7)8.如何设置X轴和Y轴的标题 (7)三、绑定数据源 (8)1.通过Chart的DataSource属性绑定数据 (8)2.通过Chart的DataBindTable方法绑定数据源 (9)3.通过Chart的DataBindCrossTable绑定数据源 (10)4.使用Chart的series属性下面的Points.DataBind方法绑定数据源 (11)5.使用Chart的Series属性下面的Points.DataBindXY方法绑定数据源 (12)一、MSChart控件的总体介绍图二、属性1.属性ChartAreas这个属性表示的是图表区域,Chart控件相当于是一个图表面板,在这个面板中可以将其分成多个图标区域,在每个图表区域中只能放置一个图表。
如下图所示:是将整个图标控件分成两个图标区域,在每个图标区域中分别有一张图表。
图中蓝色代表的是某一分组的序列记录,黄色代表的是另一分组的序列记录。
他们可以绑定不同的数据源。
2.属性ChartSeriesChartSeries表示的是一条分组记录数据,在一个图标区域中可以有多个图标序列,每条图标序列是以颜色进行区分,如上图,在每张图表中都只有一条图表序列,如下图,在上一个图表中有两个图表序列,分别代表的是两条不同的分组记录。
3.属性Legends属性Legends是对图表序列的解释,每一个图表序列都会对应着一个Legend,如下图所示:在图表右上方的图例是对图表中序列的解释,标示着三个序列分别代表的是数据。
4.怎么设置图表中X轴和Y轴的区域X轴和Y轴是属于ChartAreas这里面的,所以我们在设置X轴和Y轴的属性的时候,需要通过ChartAreas这个属性来获得这个图标的X轴和Y轴的信息。
首先在属性窗口中找到Chart控件的属性ChartAreas→点击进入到ChartAreas属性对话框,找到Axes属性→点击进入到Axes属性对话框中相应的在这个对话中我们还可以设置Y轴的最大最小值,同样还可以设置一些其他关于X 轴和Y轴的属性,如外观样式等。
图表对X轴和Y轴设置最大最小值时显示的效果:注:在我们不设置X轴和Y轴最大最小值的情况下,程序会自动根据数据源绑定X轴和Y 轴的值。
5.如何启用图表的3D显示效果设置3D效果也是将图表区域以3D的形式展现,所以在设置的时候我们一样是要访问的是ChartAreas属性,在ChartAreas属性里面进行进一步的设置。
2)通过设计器的方式显示3D效果同上一样,先找到ChartAreas这个属性对话框,选中相应的图标区域,将Area3DStyle下面的Enabled设置属性设置为true→设置3D后显示效果如下:6.如何设置图表标题每张图表都会有一个或多个标题,便于用户查看,我们通过Chart的ChartTitles这个属性来设置图表的标题。
首先找到Chart的ChartTitles这个属性→进入到Titles属性对话框进行设置→添加以后可以对添加的标题进行设置→设置标题后显示效果:7.如何设置图表线的宽度通过ChartSeries的BorderWidth属性可以设置图表序列的宽度,如下:效果:未设置前设置后8.如何设置X轴和Y轴的标题在显示数据的时候,一般我们要标明X轴和Y轴的标题,表示是对数据的一个解释,如下:三、绑定数据源1.通过Chart的DataSource属性绑定数据1)如果要通过该属性设置Chart的数据源,可以作为数据源的数据类型包括:●DataView对象●DataReader数据读取器(SQL、OleDB)●DataSet数据集●DataTable●继承自IDataSource的数据对象●数组●列表●所有Enumberable对象●SqlCommand/OleCommand(仅DataSource数据绑定)●SqlDataAdapter/OleDbDataAdapter(仅DataSource数据绑定)2)通过这个属性设置的数据源,在运行前必须设置对于X轴和Y轴要显示的数据字段如下是通过设置DataSource属性设置的数据源绑定数据:源代码:注:在这之前并未对Chart控件进行任何的设置,只是在Load事件中绑定数据源,并绑定了在X轴上和Y轴上要显示的字段,系统会自动根据绑定数据设置X轴和Y轴值的显示情况,我们也可以通过编程的方式来进行控制。
2.通过Chart的DataBindTable方法绑定数据源方法1:public voidDataBindTable(System.Collections.IEnumerable dataSource)参数中dataSource可以是上面任何一类数据源,但是通过该方法绑定的数据源,系统会自动将字段绑定到Chart图表中,如下图所示:效果图:这里是将MonthInfo作为X轴数据显示,而ID和SumData字段都作为Y轴数据进行显示了。
所以我们可以再获得数据源的SQL语句中指查找两个字段,不绑定多个字段,由此看此方法只适用于绑定两个字段的数据表。
修改后效果:这时显示的数据就是X轴显示MonthInfo字段,Y轴显示SumData字段。
方法2:public voidDataBindTable(System.Collections.IEnumerable dataSource, string xField)参数:dataSource,数据源;xField,X轴要绑定的字段。
这里系统会自动将MonthInfo绑定到X轴,将SumData字段绑定到Y轴。
3.通过Chart的DataBindCrossTable绑定数据源方法1:public v oidDataBindCrossTable(System.Collections.IE nume rable dataSource, string seriesGroupByField, string xField, string yFields, string ot herFields)dataSource:数据源seriesGroupByField:绑定用于分组的字段xField:绑定用于X轴的字段yField:绑定用于Y轴的字段otherFields:绑定用于其他属性的字段。
该方法通过设置数据源,并设置X轴和Y轴绑定的数据字段,将信息绑定到Chart中,如下:效果:程序中是以姓名作为分组的一句,将整个数据源分成四组,构成了四个series序列,每个序列即代表了一个人的成绩信息,其中X轴表示的是科目信息,Y轴表示的是成绩信息。
注意:上面方法中otherField这个参数表示的是其他属性的值,如上面程序缩写ToolTip=Stuname,表示当鼠标移到这个图表序列上时就会显示该序列代表的是哪个用户的数据,早上面图中张良就是设置了otherField这个参数后显示的效果。
方法2:public v oidDataBindCrossTable(System.Collections.IE nume rable dataSource, string seriesGroupByField, string xField, string yFields, string ot herFields, System.Windows.Forms.DataV isualiza tion.Charting.PointSortOrder s ortingOrder) sortingOrder:制定用来排序的方式,PointSortOrder是一个枚举类型,有Ascending和Descending两个值。
这个排序是根据组字段进行排序的。
这个程序中是使用StuName这个字段进行排序的。
其余同上。
方法使用:效果:未排序之前排序之后注:这里的排序只是针对每一个序列内部值的排序发生了变化。
4.使用Chart的series属性下面的Points.DataBind方法绑定数据源public voidDataBind(System.Collections.IEnumerable dataSource, string xField, string yFields, string otherFields)使用这个方法,首先必须是已经确定了的数据,而且要先添加了series序列,不管是动态添加还是通过设计器添加,与上面的几个方法相比,这个方法局限性很大。
编程案例:注:这里我们在绑定数据源的时候至绑定了学号为1的同学的成绩,如果我们把所有同学的成绩都绑在数据源里面的话,显示的时候就会把全部数据显示出来,而且是在同一个序列里面,这样就是失去了图表的作用,如下是同时绑定多个同学的成绩是出现的效果:这里把所有的记录都显示出来了,我们不能分辨那个序列式代表哪个同学的,所以此种方法只适用于那些数据源已经确定了的。
5.使用Chart的Series属性下面的Points.DataBindXY方法绑定数据源方法:public voidDataB indX Y(System.Colle ctions.IE numerable xValue, string xField, System.Collections.IE nume rable yValue, string yFields)xValue:要绑定X轴的数据源xField:绑定到X轴的字段yValue:要绑定到Y轴的数据源yFields:绑定到Y轴的字段编程实现:效果:。