C# 写一个曲线图示例
时间: 2023-10-19 07:59:18 浏览: 53
好的,以下是一个C#曲线图示例,它可以实时显示由用户输入的数据。你可以在Visual Studio中创建一个Windows Forms应用程序,然后将以下代码复制到Form1.cs文件中:
```csharp
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace ChartExample
{
public partial class Form1 : Form
{
private List<double> data = new List<double>();
public Form1()
{
InitializeComponent();
InitChart();
}
private void InitChart()
{
// 添加数据系列
chart1.Series.Add("Series1");
// 设置曲线颜色和宽度
chart1.Series["Series1"].Color = System.Drawing.Color.Blue;
chart1.Series["Series1"].BorderWidth = 2;
// 设置坐标轴标题
chart1.ChartAreas[0].AxisX.Title = "X轴";
chart1.ChartAreas[0].AxisY.Title = "Y轴";
// 设置坐标轴范围
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 10;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 100;
// 设置坐标轴刻度
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisY.Interval = 10;
// 显示网格线
chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = true;
chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
// 获取用户输入的数据
double input = 0;
if (double.TryParse(textBox1.Text, out input))
{
// 添加数据到列表
data.Add(input);
// 显示最近的10个数据
if (data.Count > 10)
{
data.RemoveAt(0);
}
// 更新曲线图
chart1.Series["Series1"].Points.Clear();
for (int i = 0; i < data.Count; i++)
{
chart1.Series["Series1"].Points.AddXY(i + 1, data[i]);
}
}
}
}
}
```
然后在窗体设计器中添加一个Chart控件、一个TextBox控件和一个Button控件,并将它们分别命名为chart1、textBox1和button1。运行程序,输入一些数字,点击按钮,即可在曲线图中实时显示最近的10个数据,如下图所示:
![实时曲线图示例](https://i.imgur.com/4rYlrnZ.png)
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)