[Yugong Series] Detailed explanation of Chart control on Winform control special topic in September 2023


Preface

Winform controls are user interface elements in Windows Forms. They can be used to create various visual and interactive components of Windows applications, such as buttons, labels, text boxes, drop-down list boxes, check boxes, radio boxes, progress bars, etc. . Developers can use Winform controls to build user interfaces and respond to user actions to create powerful desktop applications.

1. Detailed explanation of Chart control

The Chart control in Winform is a control used to create and display charts. It can easily add various types of charts in Windows Forms, such as bar charts, linear charts, pie charts, etc. Here are some basic steps for using the Chart control:

  1. Add a Chart control: Drag the Chart control from the Visual Studio Toolbox window to the Windows Form.

  2. Data binding: Bind data to the Chart control when the form loads. For example, data can be provided using a data set or data table.

  3. Add a data series: Use the Series property of the Chart control to add a data series. Each data series represents a set of data in a chart.

  4. Set the chart type: You can use the ChartType property of the Chart control to set the chart type. For example, it can be set to a bar chart, linear chart, pie chart, etc.

  5. Set the coordinate axis: You can use the Axis property of the Chart control to set the coordinate axis. For example, you can set the scale of the X coordinate axis and Y coordinate axis, etc.

  6. Set the legend: The legend is a label used to explain the contents of the chart. You can use the Legend property of the Chart control to set the legend. For example, you can set the location and display items of the legend, etc.

  7. Set style: You can use various style properties of the Chart control to modify the appearance of the chart. For example, you can modify the background color, line color, etc. of the chart.

  8. Display the chart: After all settings are completed, use the DataBind and Refresh methods of the Chart control to display the chart. The DataBind method binds data to the chart, while the Refresh method refreshes the chart's display.

Chart control is a very powerful and flexible control that can be used to create various types of charts, and provides rich properties and methods to customize the appearance and behavior of charts.

Note: In order to be cross-platform and compatible, the winform project created based on .net6 does not have a chart chart control, but it can be extended through the nuget package manager, such as: ScottPlot chart control.

1. Attribute introduction

1.1 DataSource

When using the Chart control in WinForm, you can bind the data source by setting the DataSource property. Here are some steps:

  1. First, make sure you have added the Chart control to the form designer.

  2. At design time or run time, create a data source and bind the data source to the Chart control. Any .NET data source can be used, such as DataTable, BindingSource, List, etc.

  3. In code, use the DataSource property to assign the data source to the Chart control.

For example, the following code demonstrates how to bind a DataTable to a Chart control:

chart1.Series.Clear();
Series series2 = new Series();
series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series2.LegendText = "曲线2";//设置图例文本
series2.Color = Color.Blue;//曲线的颜色
series2.BorderWidth = 2;//曲线的宽度
chart1.Series.Add(series2);
DataTable dt = new DataTable();
dt.Columns.Add("序号");
dt.Columns.Add("值");
for (int i = 0; i < 5; i++)
{
    
    
    dt.Rows.Add();
    dt.Rows[i][0] = i + 1;
    dt.Rows[i][1] = (i + 1) * 10;
}
chart1.DataSource = dt;//绑定数据源
chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
chart1.Series[0].YValueMembers = "值";//设置曲线的X轴绑定dt中的名为"值"的列

insert image description here

1.2 Annotations

The Annotations property of the Chart control is used to add annotations to the chart. It can be used to mark special data points or add some explanatory text. The Annotations property is an object of type AnnotationCollection, which contains all annotation objects.

In Winform, you can use the Annotations property through the following steps:

  1. Create a Chart control: In the toolbox of Visual Studio, find the Chart control, drag it to the form and set its properties.

  2. Add annotations: Use the Annotations property of the Chart control to add annotations, which can be achieved through the following code:

// 创建一个注释对象,并设置其属性
TextAnnotation annotation = new TextAnnotation();
annotation.Text = "这是一段注释";
annotation.ForeColor = Color.Red;
annotation.Font = new Font("宋体", 14);
annotation.X = 3;
annotation.Y = 10;

// 将注释对象添加到AnnotationCollection中
chart1.Annotations.Add(annotation);

In the above code, an annotation object of type TextAnnotation is first defined, and its text, foreground color, font, position and other properties are set. Then add the annotation object to the Annotations property of the Chart control to display the annotation on the chart.

  1. Display annotations: By setting the Visible property of the annotation object, you can control the display and hiding of annotations. For example, the following code controls the display of all comments:
foreach (var annotation in chart1.Annotations)
{
    
    
    annotation.Visible = true;
}

Use the Annotations property to easily add annotations to the chart to make the chart more descriptive and readable. If you need more complex annotation styles, you can also use other types of Annotation objects, such as LineAnnotation, RectangleAnnotation, etc.

insert image description here

1.3 ChartAreas

1.3.1 To

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();
    chartArea1.BackColor = Color.Red;

    ElementPosition elementPosition = chartArea1.Position;
    chartArea1.Position = new ElementPosition(0, 0, 50, 50);//设置的值范围时0到100,对应的0%到100%。
    chartArea1.InnerPlotPosition = new ElementPosition(0, 0, 100, 100);//不包括轴标签和刻度线
    chart1.ChartAreas.Add(chartArea1);

    ChartArea chartArea2 = new ChartArea();
    chartArea2.BackColor = Color.Yellow;
    chartArea2.Position = new ElementPosition(0, 50, 100, 50);
    chart1.ChartAreas.Add(chartArea2);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
    series2.LegendText = "曲线1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 5; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = i + 1;
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列




    Series series3 = new Series();
    series3.ChartArea = chart1.ChartAreas[1].Name;
    series3.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
    series3.LegendText = "曲线2";//设置图例文本
    series3.Color = Color.Blue;//曲线的颜色
    series3.BorderWidth = 2;//曲线的宽度
    chart1.Series.Add(series3);


    chart1.Series[1].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[1].YValueMembers = "值2";//设置曲线的X轴绑定dt中的名为"值"的列

}

insert image description here

1.3.2 3D display

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();
    chartArea1.BackColor = Color.Red;

    ElementPosition elementPosition = chartArea1.Position;
    chartArea1.Position = new ElementPosition(0, 0, 50, 50);//设置的值范围时0到100,对应的0%到100%。
    chartArea1.InnerPlotPosition = new ElementPosition(10, 10, 90, 90);//不包括轴标签和刻度线
    chartArea1.Area3DStyle.Enable3D = true;
    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Column;//柱状图
    series2.LegendText = "曲线1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 5; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = i + 1;
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列
}

insert image description here

1.3.3 Appearance

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();


    ElementPosition elementPosition = chartArea1.Position;
    //chartArea1.Position = new ElementPosition(0, 0, 50, 50);//设置的值范围时0到100,对应的0%到100%。
    //chartArea1.InnerPlotPosition = new ElementPosition(10, 10, 90, 90);//不包括轴标签和刻度线

    //外观设置
    chartArea1.Visible = true;
    chartArea1.BackColor = Color.Red;//背景色,如果BackSecondaryColor和Color属性不一样则BackColor为渐变开始的颜色
    chartArea1.BackGradientStyle = GradientStyle.None;//从左到右渐变
    chartArea1.BackSecondaryColor = Color.Yellow;//渐变结束的颜色
    chartArea1.BackHatchStyle = ChartHatchStyle.Cross;//阴影样式,颜色由BackSecondaryColor指定
    chartArea1.BackImage = @"C:\Users\Happy\Pictures\Saved Pictures\2d0e6f4495ee9cab920b2bdaeb155e37.jpeg";//设置背景图像,路径
    chartArea1.BackImageAlignment = ChartImageAlignmentStyle.TopRight;//该属性只能在BackImageWrapMode为Unscaled时使用
    chartArea1.BackImageWrapMode = ChartImageWrapMode.Scaled;//设置图像显示模式,Scaled为缩放图像让其适应图表元素大小,一般情况下是需要使用缩放的
    chartArea1.BackImageTransparentColor = Color.Red;//碰到BackImage中有透明颜色时,应该使用什么颜色替代
    chartArea1.BorderColor = Color.Yellow;//边框颜色
    chartArea1.BorderWidth = 5;//边框宽度
    chartArea1.BorderDashStyle = ChartDashStyle.DashDot;//边框线型
    chartArea1.IsSameFontSizeForAllAxes = true;//设置轴标签大小是否相等
    chartArea1.ShadowColor = Color.Goldenrod;//阴影颜色
    chartArea1.ShadowOffset = 20;//阴影偏移量
    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Column;//柱状图
    series2.LegendText = "曲线1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 5; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = i + 1;
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列
}

insert image description here

1.3.4 Cursor

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();
    chartArea1.CursorX.AutoScroll = true;//当选择范围超出当前坐标范围时,是否发生自动滚动
    chartArea1.CursorX.IsUserEnabled = true;//是否显示游标
    chartArea1.CursorX.IsUserSelectionEnabled = true;//是否允许用户使用鼠标选择范围
    chartArea1.CursorX.Position = 1.5;
    chartArea1.CursorX.Interval = 0.5;//设置当用户选择范围时,间隔多少出现游标
    chartArea1.CursorX.IntervalType = DateTimeIntervalType.Auto;//间隔的单位
    chartArea1.CursorX.IntervalOffset = 0;//没啥作用
    chartArea1.CursorX.IntervalOffsetType = DateTimeIntervalType.Auto;//没啥作用
    chartArea1.CursorX.LineColor = Color.Yellow;
    chartArea1.CursorX.LineDashStyle = ChartDashStyle.Dot;
    chartArea1.CursorX.LineWidth = 3;
    chartArea1.CursorX.SelectionColor = Color.Red;
    chartArea1.CursorX.SelectionStart = 1;
    chartArea1.CursorX.SelectionEnd = 2;


    chartArea1.AxisX.ScaleView.Zoomable = true;//是否开启缩放用户界面
    chartArea1.AxisX.ScaleView.Size = 3;//设置缩放时X坐标的显示的范围
    chartArea1.AxisX.IsMarginVisible = false;//如果为true,则在第一个点的左边增加一个空格,在最后一个点的右边也增加一个空格

    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Line;//曲线
    series2.LegendText = "曲线1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    series2.MarkerStyle = MarkerStyle.Circle;
    series2.IsValueShownAsLabel = true;
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 5; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = i + 1;
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列

}

insert image description here

1.3.5 Axis

1.3.5.1 X-axis
private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();


    //轴标签
    chartArea1.AxisX.IsMarginVisible = false;//如果为true,则在第一个点的左边增加一个空格,在最后一个点的右边也增加一个空格
    chartArea1.AxisX.IsLabelAutoFit = false;//自动调整轴标签
    chartArea1.AxisX.LabelAutoFitMaxFontSize = 10;//自动调整标签时最大字体大小
    chartArea1.AxisX.LabelAutoFitMinFontSize = 5;//自动调整标签时最小字体大小
    chartArea1.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.LabelsAngleStep30;//自动调整标签的角度范围


    //自定义标签,有时候需要把IsLabelAutoFit设置为true,不然自定义标签效果看不出来
    for (int i = 0; i < 5; i++)
    {
    
    
        int rowIndex = 0;
        CustomLabel label = new CustomLabel(i + 0.5, i + 1.5, (i + 1).ToString() + "月", rowIndex, LabelMarkStyle.None);
        chartArea1.AxisX.CustomLabels.Add(label);
    }

    chartArea1.AxisX.LabelStyle.Angle = 0;//角度
    chartArea1.AxisX.LabelStyle.Font = new Font("宋体", 15);//字体类型和大小
    chartArea1.AxisX.LabelStyle.ForeColor = Color.Red;//字体颜色
    chartArea1.AxisX.LabelStyle.Format = "F2";//感觉没什么用
    chartArea1.AxisX.LabelStyle.Interval = 1;//间隔多久显示一个标签
    chartArea1.AxisX.LabelStyle.IntervalType = DateTimeIntervalType.Auto;//标签间隔使用的单位
    chartArea1.AxisX.LabelStyle.IntervalOffset = 0;//间隔的偏移,一般不使用
    chartArea1.AxisX.LabelStyle.IntervalOffsetType = DateTimeIntervalType.Auto;//一般不使用
    chartArea1.AxisX.LabelStyle.IsEndLabelVisible = true;//是否在轴的末尾显示标签,一般是true
    chartArea1.AxisX.LabelStyle.IsStaggered = false;//如果为true,则标签显示的时候一个在上一个在下,显示为交错排列
    chartArea1.AxisX.LabelStyle.Tag = "";//可以绑定数据
    chartArea1.AxisX.LabelStyle.TruncatedLabels = true;//不知道具体作用
    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Line;//曲线
    series2.LegendText = "曲线1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    series2.MarkerStyle = MarkerStyle.Circle;
    series2.IsValueShownAsLabel = true;
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 5; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = i + 1;
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列

}

insert image description here

1.3 Legends

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();

    chartArea1.AxisX.IsMarginVisible = false;//如果该属性为true,则在第一个数据点的左边以及最后一个数据点的右边添加空格
    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Line;//曲线
    series2.LegendText = "曲线 1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    series2.MarkerStyle = MarkerStyle.Circle;
    series2.IsValueShownAsLabel = true;
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 10; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = (i + 1);
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列

    //标题
    chart1.Legends[0].Title = "图例标题";//图例标题文本
    chart1.Legends[0].TitleAlignment = StringAlignment.Center;//图例标题对齐方式
    chart1.Legends[0].TitleFont = new Font("宋体", 20); //图例标题字体类型和大小
    chart1.Legends[0].TitleBackColor = Color.Gold;//图例标题背景颜色
    chart1.Legends[0].TitleForeColor = Color.Black;//图例标题文本颜色
    chart1.Legends[0].TitleSeparator = LegendSeparatorStyle.DotLine;//图例分割线类型
    chart1.Legends[0].TitleSeparatorColor = Color.Green; //图例分割线颜色

    //停靠
    chart1.Legends[0].Alignment = StringAlignment.Near;//图例对齐方式
    chart1.Legends[0].DockedToChartArea = chartArea1.Name;
    chart1.Legends[0].Docking = Docking.Right;//图例停靠方式
    chart1.Legends[0].IsDockedInsideChartArea = false;//此时一定要设置DockedToChartArea属性
    chart1.Legends[0].MaximumAutoSize = 50;//尚不知道具体作用


    //外观
    chart1.Legends[0].Enabled = true;
    chart1.Legends[0].LegendStyle = LegendStyle.Row; //图例样式
    chart1.Legends[0].TableStyle = LegendTableStyle.Wide;//图例表样式
    chart1.Legends[0].AutoFitMinFontSize = 50;
    chart1.Legends[0].BackColor = Color.Yellow;//图例背景色开始颜色
    chart1.Legends[0].BackGradientStyle = GradientStyle.LeftRight;//渐变颜色样式
    chart1.Legends[0].BackHatchStyle = ChartHatchStyle.None;
    chart1.Legends[0].BackSecondaryColor = Color.Blue;//图例背景色结束颜色
    chart1.Legends[0].BorderColor = Color.Red; //图例边框颜色
    chart1.Legends[0].BorderWidth = 2;// 图例边框线宽
    chart1.Legends[0].BorderColor = Color.Red; //图例边框颜色
    chart1.Legends[0].BorderDashStyle = ChartDashStyle.Dash;

    chart1.Legends[0].Font = new Font("宋体", 20);
    chart1.Legends[0].ForeColor = Color.Red;
    chart1.Legends[0].InterlacedRows = false;
    chart1.Legends[0].InterlacedRowsColor = Color.Yellow;
    chart1.Legends[0].IsEquallySpacedItems = true;
    chart1.Legends[0].IsTextAutoFit = false;//图例文本自动改变大小,会导致Legends[0].Font =失效
                                            //chart1.Legends[0].Position = new ElementPosition(50,50,50,50);//设置图例位置
    chart1.Legends[0].ShadowColor = Color.Yellow;
    chart1.Legends[0].ShadowOffset = 0;
    chart1.Legends[0].TextWrapThreshold = 2;//当图例文本超过此属性指定的值时,遇到下一个空格字符时,文本将自动换行。如果文本中没有空格字符,则不会换行。将TextWrapThreshold属性设置为零可禁用该功能


}

insert image description here

1.4 Title

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.Titles.Clear();
    Title title = new Title();
    chart1.Titles.Add(title);
    title.Alignment = ContentAlignment.MiddleCenter;//标题显示的位置
    title.BackColor = Color.Red;//背景色
    title.BorderColor = Color.Blue;//边框颜色
    title.DockedToChartArea = chart1.ChartAreas[0].Name;//停靠在那个ChartAreas边上
    title.Docking = Docking.Top;//停靠方式
    title.Font = new Font("宋体", 20);//字体
    title.ForeColor = Color.Green;//字体颜色
    title.IsDockedInsideChartArea = true;//是否在ChartArea 里面显示
    title.Text = "曲线";//标题文本
    title.TextOrientation = TextOrientation.Horizontal;//标题显示方向
    title.TextStyle = TextStyle.Emboss;//标题样式
    title.Visible = true;//是否显示标题

    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();




    chartArea1.AxisX.IsMarginVisible = false;//如果该属性为true,则在第一个数据点的左边以及最后一个数据点的右边添加空格
    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();
    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Line;//曲线
    series2.LegendText = "曲线 1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度
    series2.MarkerStyle = MarkerStyle.Circle;
    series2.IsValueShownAsLabel = true;
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 10; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = (i + 1);
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列

}

insert image description here

1.5 Series

private void Form1_Load(object sender, EventArgs e)
{
    
    
    chart1.ChartAreas.Clear();
    ChartArea chartArea1 = new ChartArea();

    chartArea1.AxisX.IsMarginVisible = false;//如果该属性为true,则在第一个数据点的左边以及最后一个数据点的右边添加空格
    chart1.ChartAreas.Add(chartArea1);

    chart1.Series.Clear();
    Series series2 = new Series();

    //标记
    series2.MarkerBorderColor = Color.Blue;//标记边框颜色
    series2.MarkerBorderWidth = 2;//标记边框宽度
    series2.MarkerColor = Color.Red;//标记颜色
    series2.MarkerStyle = MarkerStyle.Circle;//标记类型
    series2.MarkerSize = 10;//标记尺寸
    series2.MarkerStep = 2;//多少间隔显示一个标记
    //series2.MarkerImage =@"C:\Users\zhaij\Desktop\香蕉.jpg";//需要设置图像尺寸和标记大小相同,不然图像太大,该属性基本不用


    series2.ChartArea = chart1.ChartAreas[0].Name;
    series2.ChartType = SeriesChartType.Line;//曲线
    series2.LegendText = "曲线1";//设置图例文本
    series2.Color = Color.Green;//曲线的颜色
    series2.BorderWidth = 2;//曲线的宽度

    series2.IsValueShownAsLabel = true;
    chart1.Series.Add(series2);
    DataTable dt = new DataTable();
    dt.Columns.Add("序号");
    dt.Columns.Add("值1");
    dt.Columns.Add("值2");
    for (int i = 0; i < 10; i++)
    {
    
    
        dt.Rows.Add();
        dt.Rows[i][0] = (i + 1);
        dt.Rows[i][1] = (i + 1) * 10;
        dt.Rows[i][2] = (i + 1) * 100;
    }
    chart1.DataSource = dt;//绑定数据源
    chart1.Series[0].XValueMember = "序号";//设置曲线的X轴绑定dt中的名为"序号"的列
    chart1.Series[0].YValueMembers = "值1";//设置曲线的X轴绑定dt中的名为"值"的列


}

insert image description here

2. Common scenarios

The Chart control in Winform is a data visualization tool that can be used to display various statistical charts and data charts. The following are common scenarios for the Chart control:

  1. Data analysis and visualization: The Chart control can be used to display various data charts, such as line charts, histograms, pie charts, scatter charts, etc., to facilitate users to better understand and analyze data.

  2. Real-time monitoring: Chart controls can be used to display data trends in real time, such as stock quotes, weather data, etc., with high real-time and fast response capabilities.

  3. Testing and debugging: The Chart control can be used to test and debug various algorithms and models, such as machine learning algorithms, image processing algorithms, etc., so that users can better understand the working principles and effects of the algorithms.

  4. Product display: Chart controls can be used to display the sales and trends of various products, such as e-commerce platforms, real-time online games, etc., so that users can better understand the market performance and trends of products.

Chart controls are widely used in data visualization and data analysis, and can greatly improve users' data analysis efficiency and work efficiency.

3. Specific cases

We can use the Yahoo Finance API to obtain real-time stock data and display the data in the Chart control. First, the following namespaces need to be introduced:

using System.Windows.Forms.DataVisualization.Charting;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

Then, when the control is initialized, you can set the properties of the Chart, such as title, axis, chart type, etc.:

private void Form1_Load(object sender, EventArgs e)
{
    
    
    // 设置Chart属性
    chart1.Titles.Add("股票价格走势图");
    chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
    chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightGray;
    chart1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd";
    chart1.Series.Clear();
}

Next, you can write a method to get the stock data and add the data to the Chart's data series:

private void GetStockData(string symbol)
{
    
    
    // 获取股票数据
    string url = String.Format("https://query1.finance.yahoo.com/v7/finance/chart/{0}?range=1d&interval=5m", symbol);
    WebClient client = new WebClient();
    Stream stream = client.OpenRead(url);
    StreamReader reader = new StreamReader(stream);
    string json = reader.ReadToEnd();
    JObject stockData = JObject.Parse(json);

    // 添加数据系列
    JArray prices = (JArray)stockData["chart"]["result"][0]["indicators"]["quote"][0]["close"];
    List<double> priceList = prices.Select(p => (double)p).ToList();
    DateTime startDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    JArray timestamps = (JArray)stockData["chart"]["result"][0]["timestamp"];
    List<DateTime> timeList = new List<DateTime>();
    foreach (long timestamp in timestamps)
    {
    
    
        DateTime dateTime = startDate.AddMilliseconds(timestamp);
        timeList.Add(dateTime);
    }
    Series series = new Series(symbol);
    series.XValueType = ChartValueType.DateTime;
    for (int i = 0; i < priceList.Count; i++)
    {
    
    
        series.Points.AddXY(timeList[i], priceList[i]);
    }
    chart1.Series.Add(series);
}

Finally, on the button click event, you can call this method to get the data and add it to the Chart control:

private void button1_Click(object sender, EventArgs e)
{
    
    
    GetStockData(textBox1.Text);
}

In this way, real-time stock data can be displayed through the Chart control.

insert image description here

Guess you like

Origin blog.csdn.net/aa2528877987/article/details/132754997