c# chart曲线
时间: 2025-02-14 09:13:17 浏览: 31
### 创建和自定义曲线图表
在 C# WinForms 应用程序中创建和自定义带有多个 Y 轴的 2D 数据曲线显示控件可以通过使用 `System.Windows.Forms.DataVisualization.Charting` 命名空间中的类来实现[^1]。
#### 添加命名空间引用
为了能够访问 Chart 控件的功能,项目需要添加对 `System.Windows.Forms.DataVisualization.dll` 的引用。这通常通过 NuGet 包管理器安装完成。
#### 初始化 Chart 控件
Chart 控件可以被拖放到设计器上或者编程方式实例化并设置其属性:
```csharp
using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
public class CustomChartForm : Form {
private Chart chart;
public CustomChartForm() {
InitializeComponents();
}
private void InitializeComponents() {
// Create and configure the chart control.
chart = new Chart();
chart.Dock = DockStyle.Fill;
var chartArea = new ChartArea("Main");
chart.ChartAreas.Add(chartArea);
Controls.Add(chart);
}
}
```
#### 配置多条 Y 轴
对于具有三个独立 Y 轴的需求,在 ChartArea 对象内配置额外的 AxisY 实例,并指定它们的位置以及关联的数据序列:
```csharp
// Add primary Y axis (left side).
chartArea.AxisY.Title = "Primary Voltage";
chartArea.AxisY.LineColor = Color.Black;
// Add secondary Y axes on right side of plot area.
var yAxisSecondaryCurrent = new Axis("AxisY2", AxisName.Y, true);
yAxisSecondaryCurrent.Title = "Current";
yAxisSecondaryCurrent.LineColor = Color.Blue;
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.MajorGrid.LineDashStyle = ChartDashStyle.DashDot;
chartArea.AxisY2.LabelAutoFitMinFontSize = 8;
var yAxisTertiaryPower = new Axis("AxisY3", AxisName.Y, false);
yAxisTertiaryPower.Title = "Power";
yAxisTertiaryPower.LineColor = Color.Red;
chartArea.AxisY3.Enabled = AxisEnabled.True;
chartArea.AxisY3.IsStartedFromZero = false;
chartArea.AxisY3.IntervalOffsetType = DateTimeIntervalType.Number;
```
#### 绘制实时更新的电压电流轨迹曲线
为了让图表支持动态数据输入,可以在后台线程定时向 Series 中追加新点位,同时移除过期的数据点保持窗口滚动效果:
```csharp
private Timer timerUpdateDataPoints;
private Random randomGenerator = new();
timerUpdateDataPoints = new(100);
timerUpdateDataPoints.Elapsed += OnTimerTick;
timerUpdateDataPoints.Start();
void OnTimerTick(object sender, EventArgs e) {
double voltageValue = GetVoltageReading(); // Replace with actual data source method call
double currentValue = GetCurrentReading(); // Replace with actual data source method call
seriesVoltage.Points.AddXY(DateTime.Now.ToOADate(), voltageValue);
seriesCurrent.Points.AddXY(DateTime.Now.ToOADate(), currentValue);
if(seriesVoltage.Points.Count > MAX_POINTS){
seriesVoltage.Points.RemoveAt(0);
seriesCurrent.Points.RemoveAt(0);
}
this.Invoke((MethodInvoker)this.chart.Invalidate);
}
double GetVoltageReading(){
return Math.Sin(randomGenerator.NextDouble()) * VOLTAGE_AMPLITUDE + BASE_VOLTAGE_LEVEL;
}
double GetCurrentReading(){
return Math.Cos(randomGenerator.NextDouble()) * CURRENT_AMPLITUDE + BASE_CURRENT_LEVEL;
}
```
阅读全文
相关推荐
















