且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#图表中添加两个不同的类型系列?

更新时间:2023-11-23 23:43:58

您的问题很可能来自于您准备系列 之前将它们添加到图表中。

Most likely your problems come from the way you prepare the Series before adding them to the Chart.

我发现在将股票系列添加到图表之前,我什至无法添加点!我得到的错误声称我只能为 DataPoints 添加一个y值,这显然是错误的,因为 SeriesChartType.Stock 已经设置。

I found that I can't even add points to a Stock series before it has been added to the chart! The error I got, claimed that I could only add one y-value for my DataPoints, which was obviously wrong, as the SeriesChartType.Stock had already been set.

因此,请尝试以下命令:

So try this order:

chart1.Series.Clear();

string seriesName1 = "stock";
Series ser1 =  chart1.Series.Add(seriesName1);

ser1.ChartArea = chart1.ChartAreas[0].Name;
ser1.Name = seriesName1;
ser1.ChartType = SeriesChartType.Stock;

ser1.BorderWidth = 3;

ser1.Points.AddXY(1, 44, 11, 34, 37);  // x, high, low, open, close
ser1.Points.AddXY(2, 33, 11, 22, 33);


string seriesName2 = "line";
Series ser2 = chart1.Series.Add(seriesName2);

ser2.ChartArea = chart1.ChartAreas[0].Name;
ser2.Name = seriesName2;
ser2.ChartType = SeriesChartType.Line;
ser2.Points.AddXY(1, 44);
ser2.Points.AddXY(2, 33);

还要确保 seriesName 变量包含正确的字符串!

Also do make sure the seriesName variable contains a proper string!

更新

看到目前为止发布的完整代码,看来您正在添加一个或多个 Series ChartArea 默认,其中已经包含索引系列(系列1)。仅当该 ChartArea 中的全部(其他)系列时,才允许这样做与第一个对齐,即包含相同数量的值。由于您只添加了2个 DataPoints ,所以我怀疑它们是..

Looking at the full code posted so far it seems that you are adding one or more Series to the ChartArea "Default", which already contains an Indexed Series ("Series1"). This is only allowed if all (other) Series in that ChartArea are aligned with the first one, i.e. contain the same number of values. Since you only add 2 DataPoints, I doubt they are..

MSDN:


将Series.IsXValueIndexed属性设置为true会导致分配给同一图表区域的所有系列

的X轴(主要或次要)被索引。您必须确保系列对齐。否则,
Chart控件将引发异常。有关更多信息,请参见
对齐数据。

Setting the Series.IsXValueIndexed property to true causes all series assigned to the same chart area and X axis (primary or secondary) to be indexed. You must make sure that the series are aligned. Otherwise, the Chart control throws an exception. For more information, see Aligning Data.

注意

当尝试显示未对齐的系列以及有索引的系列时,您可以选择以下任一方式:

When trying to show an unaligned Series along with an indexed one you can get either:


  • ,解释问题(从VS运行时)

  • 或者从exe运行时或在try-catch块中忽略异常时,红色X不解释任何问题。