1.控件基本设置
chart1.ChartAreas[0].AxisY.IsStartedFromZero = false; //设置Y轴自适应chart1.Series["瞬时值"].BorderWidth = 2; // 设置曲线宽度为2个像素,注意[]中写入的Series的Namechart1.Series["瞬时值"].Color = Color.Red; // 设置曲线显示颜色chart1.ChartAreas[0].AxisX.Minimum = 0; //设置X轴最小值chart1.ChartAreas[0].AxisX.Maximum = 100;//设置X轴最大值//chart1.ChartAreas[0].AxisX.Minimum = Double.NaN;//设置X轴最小值为自适应//chart1.ChartAreas[0].AxisX.Maximum = Double.NaN;//设置X轴最小值为自适应chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;//取消chart1X轴方向显示单元格chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;//取消chart1Y轴方向显示单元格chart1.Series[0].Points.Clear(); //清除控件上所有点位chart1.Update(); //刷新控件显示chart1.Series[0].Points.RemoveAt(0); //每次移除最早的点,需要配合显示的点数使用
2.曲线鼠标滚轮缩放
// 添加鼠标滚轮事件 在窗体加载时进行绑定chart1.MouseWheel += Chart1_MouseWheel;private void Chart1_MouseWheel(object sender, MouseEventArgs e){// 获取鼠标滚轮的滚动方向int delta = e.Delta;// 根据滚动方向进行放大或缩小if (delta < 0){// 放大图表chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset();chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset();}else if (delta > 0){// 缩小图表double xMin = chart1.ChartAreas[0].AxisX.ScaleView.ViewMinimum;double xMax = chart1.ChartAreas[0].AxisX.ScaleView.ViewMaximum;double yMin = chart1.ChartAreas[0].AxisY.ScaleView.ViewMinimum;double yMax = chart1.ChartAreas[0].AxisY.ScaleView.ViewMaximum;double posXStart = chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X) - (xMax - xMin) / 3;double posXFinish = chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X) + (xMax - xMin) / 3;double posYStart = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y) - (yMax - yMin) / 3;double posYFinish = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y) + (yMax - yMin) / 3;chart1.ChartAreas[0].AxisX.ScaleView.Zoom(posXStart, posXFinish);chart1.ChartAreas[0].AxisY.ScaleView.Zoom(posYStart, posYFinish);}}
3.1 曲线添加数据(添加X轴和Y轴点位)
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; //设置曲线样式为线条chart1.Series[0].BorderWidth = 2; // 设置曲线宽度为2个像素,注意[]中写入的Series的Namechart1.Series[0].Color = Color.Red; // 设置曲线显示颜色chart1.Series[0].Name = "Test"; //设置曲线名称for (int i = 0; i < 10; i++){chart1.Series[0].Points.AddXY(i, i*2); //添加点位}
运行结果:
3.2曲线添加数据(添加Y轴点位)
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; //设置曲线样式为线条chart1.Series[0].BorderWidth = 2; // 设置曲线宽度为2个像素,注意[]中写入的Series的Namechart1.Series[0].Color = Color.Red; // 设置曲线显示颜色chart1.Series[0].Name = "Test"; //设置曲线名称chart1.Series[0].Points.AddY(0);//添加点位chart1.Series[0].Points.AddY(20);//chart1.Series[0].Points.AddY(10);//添加点位chart1.Series[0].Points.AddY(0);//添加点位
运行结果: