C#使用DevExpress中的XtraCharts控件实现图表
作者:springsnow
这篇文章介绍了C#使用DevExpress中的XtraCharts控件实现图表的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、总体概述
官方文档:
https://docs.devexpress.com/WindowsForms/8117/controls-and-libraries/chart-control
ChartControl控件主要包括Chart Title、Legend、Annotations、Diagram、Series五部分;如图:
二、chartControl层\XYDiagram层
chartControl像DEV的其它控件一样,这一层之相当于是一个壳子,我们平时在这里面设置的属性也不多。而且都是些常规属性,比如大小、停靠方式等等。
XYDiagram这一层就比较关键了,主要是涉及到XY轴的显示方式和滚动条显示等。并且坐标轴的显示方式和数据类型也有很大的关系,主要包括3种类型,数据类型是根据添加到Series中的数据类型决定的,主要属性是ArgumentScaleType。所以涉及到3种不同的设置方式。
1.当坐标轴的数据类型是数字时
2. 当前数据类型是字符串时
其它设置同上,主要是要想出现滚动条,在设计面板中还不能实现,必须通过代码设置
DevExpress.XtraCharts.XYDiagram xyDiagram1 = (XYDiagram)this.chartControl1.Diagram; xyDiagram1.AxisX.Range.MaxValueInternal = 3; //这个属性在设计视图里面是看不到的,只有代码里面才可以设置。 xyDiagram1.AxisX.Range.MinValueInternal = -0.5D;
3.当前数据类型是时间
AxisX ax = (XYDiagram)chartControl1.Diagram; ax.GridSpacingAuto = false; ax.DateTimeMeasureUnit = DateTimeMeasurementUnit.Minute;//这个可以根据你自己的情况设置 ax.DateTimeGridAlignment = DateTimeMeasurementUnit.Second; //这个是间隔单位 ax.GridSpacing = 10; // 每10秒为一个间隔。
三、实例
1.饼状图
1.1、添加ChartControl控件
在工具箱中找到ChartControl控件,拖到窗口中,创建Pie;
1.2、准备数据
private DataTable CreateChartData() { DataTable dtData = SqlHelper.GetDataSet(sql, parameters).Tables[0]; DataTable table = new DataTable("Table1"); table.Columns.Add("Name", typeof(String)); table.Columns.Add("Value", typeof(Double)); foreach (DataRow item in dtData.Rows) { var array = new object[] { item["value_num"], item["count"] }; table.Rows.Add(array); } return table; }
数据可以自定义,返回类型为DataTable即可。
1.3、根据数据创建饼状图
/// <summary> /// 根据数据创建一个饼状图 /// </summary> /// <returns></returns> private void BuilderDevChart() { //清空ChartControl控件 chartControl1.Series.Clear(); Series _pieSeries = new Series("学生成绩饼状图", ViewType.Pie); _pieSeries.ArgumentDataMember = "Name"; //绑定图表的横坐标 _pieSeries.ValueDataMembers[0] = "Value"; //绑定图表的纵坐标坐标 _pieSeries.DataSource = CreateChartData(CourseID); chartControl1.Series.Add(_pieSeries); chartControl1.AddTitle("学生成绩饼状图"); _pieSeries.LegendPointOptions.PointView = PointView.ArgumentAndValues; ChartUtils.SetPieNumber(_pieSeries); }
1.4、设置饼状Series显示方式(值/百分比)
/// <summary> /// 饼状Series设置成百分比显示 /// </summary> /// <param name="series">Series</param> public static void SetPiePercentage(this Series series) { if (series.View is PieSeriesView) { ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = true; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Percent; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0; } } /// <summary> /// 饼状Series设置显示格式,是以数字还是百分号显示 /// </summary> /// <param name="series">Series</param> public static void SetPieNumber(Series series) { if (series.View is PieSeriesView) { //设置为值 ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = false; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Number; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0; } }
实现结果:
2.柱状图
2.1、添加ChartControl控件
在工具箱中找到ChartControl控件,拖到窗口中,创建Bar:
2.2、准备数据
/// <summary> /// 创建数据 /// </summary> /// <returns></returns> private DataTable CreateBarData() { string sql = string.Format(@" SELECT c.CollegeName,COUNT(*) FROM studentmanager.student LEFT JOIN college AS c ON c.CollegeID=student.CollegeID GROUP BY c.CollegeID"); DataSet ds = _db.GetResult(sql); if (ds != null) { DataTable dtData = ds.Tables[0]; DataTable table = new DataTable("Table1"); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Value", typeof(int)); foreach (DataRow item in dtData.Rows) { var array = new object[] { item["CollegeName"], item["COUNT(*)"] }; table.Rows.Add(array); } return table; } else { return null; } }
数据可以自定义,返回类型为DataTable即可。
2.3、根据数据创建柱状图
private void BuilderDevBarChart() { chartControl2.Series.Clear(); Series _barSeries = new Series("", ViewType.Bar); _barSeries.ArgumentDataMember = "Name";//x轴 _barSeries.ValueDataMembers[0] = "Value";//Y轴 _barSeries.DataSource = CreateBarData(); _barSeries.SetColorEach(true); chartControl2.Series.Add(_barSeries); _barSeries.LegendPointOptions.PointView = PointView.ArgumentAndValues; chartControl2.SetXLableAngle(-35); chartControl2.SetCrosshair(true); chartControl2.Legend.Direction = LegendDirection.LeftToRight; chartControl2.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center; chartControl2.Legend.AlignmentVertical = LegendAlignmentVertical.BottomOutside; chartControl2.AddTitle("学院学生数量柱状图"); }
2.4、用到的方法
public static class ChartUtils { /// <summary> /// 增加数据筛选 /// </summary> /// <param name="SeriesBase">Series</param> /// <param name="columnName">列名称</param> /// <param name="value">列名称对应的筛选数值</param> /// <param name="dataFilterCondition">DataFilterCondition枚举</param> public static void AddDataFilter(this SeriesBase series, string columnName, object value, DataFilterCondition dataFilterCondition) { series.DataFilters.Add(new DataFilter(columnName, value.GetType().FullName, dataFilterCondition, value)); } /// <summary> /// 设置X轴Lable角度 /// </summary> /// <param name="chart">ChartControl</param> /// <param name="angle">角度</param> public static void SetXLableAngle(this ChartControl chart, int angle) { XYDiagram _xyDiagram = (XYDiagram)chart.Diagram; if (_xyDiagram != null) _xyDiagram.AxisX.Label.Angle = angle; } /// <summary> /// 设置Y轴Lable角度 /// </summary> /// <param name="chart">ChartControl</param> /// <param name="angle">角度</param> public static void SetYLableAngle(this ChartControl chart, int angle) { XYDiagram _xyDiagram = (XYDiagram)chart.Diagram; _xyDiagram.AxisY.Label.Angle = angle; } /// <summary> /// 设置ColorEach /// </summary> /// <param name="chart">ChartControl</param> /// <param name="colorEach">是否设置成ColorEach</param> public static void SetColorEach(this Series series, bool colorEach) { SeriesViewColorEachSupportBase colorEachView = (SeriesViewColorEachSupportBase)series.View; if (colorEachView != null) { colorEachView.ColorEach = colorEach; } } /// <summary> /// 设置是否显示十字标线 /// </summary> /// <param name="chart">ChartControl</param> /// <param name="crosshair">是否显示十字标线</param> public static void SetCrosshair(this ChartControl chart, bool crosshair) { chart.CrosshairEnabled = crosshair ? DefaultBoolean.True : DefaultBoolean.False; chart.CrosshairOptions.ShowArgumentLabels = crosshair; chart.CrosshairOptions.ShowArgumentLine = crosshair; chart.CrosshairOptions.ShowValueLabels = crosshair; chart.CrosshairOptions.ShowValueLine = crosshair; } /// <summary> /// 新增ChartControl的Title文字 /// </summary> /// <param name="chart">ChartControl</param> /// <param name="title">Title文字</param> public static void AddTitle(this ChartControl chart, string title) { chart.Titles.Clear(); //先清除以前的标题 ChartTitle _title = new ChartTitle(); _title.Text = title; chart.Titles.Add(_title); } /// <summary> /// 饼状Series设置成百分比显示 /// </summary> /// <param name="series">Series</param> public static void SetPiePercentage(this Series series) { if (series.View is PieSeriesView) { ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = true; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Percent; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0; } } /// <summary> /// 饼状Series设置显示格式,是以数字还是百分号显示 /// </summary> /// <param name="series">Series</param> public static void SetPieNumber(Series series) { if (series.View is PieSeriesView) { //设置为值 ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = false; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Number; ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0; } } /// <summary> /// ChartControl设置标题 /// </summary> /// <param name="chartControl"></param> /// <param name="HTitle"></param> public static void SetHZTitle(ref ChartControl chartControl, string HTitle) { chartControl.Titles.Clear(); //先清除以前的标题 //横标题设置 ChartTitle titles = new ChartTitle(); //声明标题 titles.Text = HTitle; //名称 titles.TextColor = System.Drawing.Color.Black; //颜色 titles.Indent = 5; //设置距离 值越小柱状图就越大 titles.Font = new Font("Tahoma", 14, FontStyle.Bold); //设置字体 titles.Dock = ChartTitleDockStyle.Top; //设置对齐方式 titles.Alignment = StringAlignment.Center; //居中对齐 chartControl.Titles.Add(titles); //添加标题 } }
实现结果:
四、事件
1、CustomDrawAxisLabel : 接管此事件来获得轴标签。定制轴标签
private void chartControl1_CustomDrawAxisLabel(object sender, CustomDrawAxisLabelEventArgs e) { AxisBase axis = e.Item.Axis; if (axis is AxisY || axis is AxisY3D || axis is RadarAxisY) { double axisValue = (double)e.Item.AxisValue; if (axisValue < 0) { e.Item.TextColor = Color.Red; } else if (axisValue > 0) { e.Item.Text = "+" + e.Item.Text; e.Item.TextColor = Color.Green; } else if (axisValue == 0) { e.Item.Text = "Zero"; } } }
2、ObjectHotTracked:鼠标指针悬停位置
private void chartControl1_ObjectHotTracked(object sender, HotTrackEventArgs e) { if (e.AdditionalObject is AxisTitle) { MessageBox.Show(e.AdditionalObject.GetType().ToString()); } }
3、CustomDrawSeries :自定义绘制系列
private void chartControl1_CustomDrawSeries(object sender, CustomDrawSeriesEventArgs e) { // Find all Bar Series by their view type,and fill them with Aqua color. if (e.Series.View is BarSeriesView) e.SeriesDrawOptions.Color = Color.Aqua; // Find the series by its name, and change its line style to dash-dot-dot. (Here it's assumed that the series view type is LineSeriesView). if (e.Series.Name == "Line Series") ((LineDrawOptions)e.SeriesDrawOptions).LineStyle.DashStyle = DevExpress.XtraCharts.DashStyle.DashDotDot; // Find all Point Series by the type of its DrawOptions, and change their marker kind to diamond. if (e.SeriesDrawOptions.GetType() == typeof(PointDrawOptions)) ((PointDrawOptions)e.SeriesDrawOptions).Marker.Kind = MarkerKind.Diamond; }
4、CustomDrawSeriesPoint:自定义绘制系列点
private void chartControl1_CustomDrawSeriesPoint(object sender, CustomDrawSeriesPointEventArgs e) { // These changes will be applied to Bar Series only. BarDrawOptions drawOptions = e.SeriesDrawOptions as BarDrawOptions; if (drawOptions == null) return; // Get the fill options for the series point. drawOptions.FillStyle.FillMode = DevExpress.XtraCharts.FillMode.Gradient; RectangleGradientFillOptions options = drawOptions.FillStyle.Options as RectangleGradientFillOptions; if (options == null) return; // Get the value at the current series point. double val = e.SeriesPoint[0]; // If the value is less than 1, hide the point's label. if (e.SeriesPoint[0] < 1) { e.LabelText = ""; } // If the value is less than 2.5, then fill the bar with green colors. if (val < 2.5) { options.Color2 = Color.FromArgb(154, 196, 84); drawOptions.Color = Color.FromArgb(81, 137, 3); drawOptions.Border.Color = Color.FromArgb(100, 39, 91, 1); } // ... if the value is less than 5.5, then fill the bar with yellow colors. else if (val < 5.5) { options.Color2 = Color.FromArgb(254, 233, 124); drawOptions.Color = Color.FromArgb(249, 170, 15); drawOptions.Border.Color = Color.FromArgb(60, 165, 73, 5); } // ... if the value is greater, then fill the bar with red colors. else { options.Color2 = Color.FromArgb(242, 143, 112); drawOptions.Color = Color.FromArgb(199, 57, 12); drawOptions.Border.Color = Color.FromArgb(100, 155, 26, 0); } }
五、导出
1、导出为PDF:
图表会被自动拆分,
if (chartControlidx.IsPrintingAvailable) //是否能被打印或输出 { // Exports to a PDF file. chartControlidx.ExportToPdf(path); // Exports to a stream as PDF. System.IO.FileStream pdfStream = new System.IO.FileStream(path, System.IO.FileMode.Create); chartControlidx.ExportToPdf(pdfStream); //... pdfStream.Close(); }
2、导出为图像文件:
if (chartControlidx.IsPrintingAvailable) //是否能被打印或输出 { // Create an image in the specified format from the chart and save it to the specified path. chartControlidx.ExportToImage(path, System.Drawing.Imaging.ImageFormat.Png); //png格式 }
六、参考
WinForm使用DecExpress控件中的ChartControl插件绘制图表
到此这篇关于C#使用XtraCharts控件实现图表的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。