一、总体概述

官方文档:

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格式
}

六、参考

https://www.cnblogs.com/Mr-Li-2016/p/6115089.html

DevExpress20:XtraCharts控件实现图表的更多相关文章

  1. ZedGrap控件绘制图表曲线

    问题描述: 使用C#中ZedGrap控件绘制图表曲线图 ZedGrap 介绍说明:     安装ZedGrap控件 ZedGraph控件dll文件: 添加ZedGraph控件,首先在新建立的C#图像工 ...

  2. 【转】使用DevExpress的WebChartControl控件绘制图表(柱状图、折线图、饼图)

    第一次写博,没什么经验,主要是把最近自己对Dev的一些研究贴出来大家共同探讨,有不足之处望大家帮忙斧正. WebChartControl是DevExpress控件群下的一个Web图表控件,它使用非常的 ...

  3. WinForm DevExpress使用之ChartControl控件绘制图表二——进阶

    1. 多坐标折线图 在这个项目中,我需要做不同采集地方和不同数据类型的数据对比,自然而然就用到了多重坐标轴,多重坐标轴可以是多个X轴,也可以是Y轴,它们的处理方式类似.本文通过项目中的实际例子介绍多重 ...

  4. DevExpress使用之ChartControl控件绘制图表(多坐标折线图、柱状图、饼状图)

    最近因为公司项目需要用到WinForm的DecExpress控件,在这里把一些使用方法总结一下. DevExpress中有一个专门用来绘制图表的插件ChartControl,可以绘制折线图.饼状图.柱 ...

  5. DevExpress ChartControl控件实现图表【转】

    1.饼状图图 1.1添加ChartControl控件 在工具箱中找到ChartControl控件,拖到窗口中,创建Pie: 1.2准备数据 private DataTable CreateChartD ...

  6. WinForm DevExpress使用之ChartControl控件绘制图表一——基础

    最近因为公司项目需要用到WinForm的DecExpress控件,在这里把一些使用方法总结一下. DevExpress中有一个专门用来绘制图表的插件ChartControl,可以绘制折线图.饼状图.柱 ...

  7. Excel绘制动态图表 之 极品offset、多种控件动态动图

    1.案例1:辅助区域动态图 动态按钮“投资金额”的制作: "数据"菜单下"数据工作”组中的“数据验证”,选择"序列". 2. OFFSET ——函数中 ...

  8. Web打印控件

    Lodop是什么? 有人说她是Web打印控件,因为她能打印.在浏览器中以插件的形式出现,用简单一行语句就把整个网页打印出来: 有人说她是打印编程接口,因为她介于浏览器和打印设备之间,是个通道和桥梁,几 ...

  9. WPF第三方控件盘点

    WPF统一的编程模型.语言和框架,实现了界面设计人员和开发人员工作可以分离的境界,鉴于WPF强大的优势,且一直是开发者关注的地方,下面和大家分享基于WPF项目开发需要用到的第三方控件,包括业界最受好评 ...

随机推荐

  1. MySQL必知必会2

    使用数据处理函数 函数 与其他大多数计算机语言一样,SQL支持利用函数来处理数据.函数一般是在数据上执行的,他给数据的转换和处理提供了方便,在前一章中用来去掉尾空格的RTrim()就是一个函数的例子 ...

  2. Linux中的13个基本Cat命令示例

    cat(“ concatenate ”的缩写)命令是Linux / Unix等操作系统中最常用的命令之一.cat命令允许我们创建单个或多个文件,查看文件包含,连接文件以及在终端或文件中重定向输出.在本 ...

  3. Nmap使用总结

    参考链接: https://nmap.org/man/zh/ http://www.360doc.com/content/18/0127/18/52402560_725574428.shtml 0X0 ...

  4. 51单片机局部变量占用ram的问题

    51单片机局部变量占用ram的问题 一.问题 自从工作以来基本不使用51或者增强型51之类的单片机.最近调试芯圣HC89S003F4增强型51,移植了32的实用代码,结果发现RAM爆了!!! 二.实践 ...

  5. logrus 剖析之 formatter

    使用 logrus 通过 formatter 来定义输出日志的格式,具体例子如下: package main import ( log "github.com/Sirupsen/logrus ...

  6. 深度自适应增量学习(Incremental Learning Through Deep Adaptation)

    深度自适应增量学习(Incremental Learning Through Deep Adaptation) 2018-05-25 18:56:00 木呆呆瓶子 阅读数 10564  收藏 更多 分 ...

  7. caffe层解读-softmax_loss

    转自https://blog.csdn.net/shuzfan/article/details/51460895. Loss Function softmax_loss的计算包含2步: (1)计算so ...

  8. cocos版本说明

    一直知道cocos是做游戏的,想学习一下,结果去官网一看就懵逼了.Cocos Creator,Cocos2d-x,cocos studio,Cocos2d-js,Cocos2d-x-lua,那一种才是 ...

  9. Oracle.EntityFrameworkCore使用时报错:Specified cast is not valid

    我用的是:Oracle.EntityframeworkCore 2.19.30 如果看到报错:System.InvalidCastException:“Specified cast is not va ...

  10. kubernetes第七章--管理存储资源