如何仅在同一图表系列中的特定点之间绘制线条

时间:2015-08-14 04:49:59

标签: c# plot charts

我有以下问题:

  • 在点图上绘制点的分布;
  • 其中一些点需要以某种方式相互连接 单个点可以连接到几个不同的点;
  • 这些点需要用一条线连接;
  • 并非所有点都可以连接。

1 个答案:

答案 0 :(得分:2)

一个系列可以 类型为Point Line,因此我们需要使用两个系列或采取一些技巧。

我建议使用两个系列,因为编码和维护起来相当简单..

enter image description here

此屏幕截图显示了100个随机点和25个随机连接。

Line图表只能绘制一条行,一个接一个地连接所有点。所以诀窍是在线系列中添加两个点,在不可见颜色和一些可见颜色之间交替颜色..:

首先,我们设置Chart及其两个Series和一个不错的Legend

chart1.Series.Clear();
ChartArea CA = chart1.ChartAreas[0];
// the series with all the points
Series SP = chart1.Series.Add("SPoint");
SP.ChartType = SeriesChartType.Point;
SP.LegendText = "Data points";
// and the series with a few (visible) lines:
Series SL = chart1.Series.Add("SLine");
SL.ChartType = SeriesChartType.Line;
SL.Color = Color.DarkOrange;
SL.LegendText = "Connections";

现在我们创建一些随机数据;你将不得不适应你的数据源..:

Random R = new Random(2015);  // I prefer repeatable randoms

List<PointF> points = new List<PointF>();  // charts actually uses double by default
List<Point> lines = new List<Point>();

int pointCount = 100;
int lineCount = 25;

for (int i = 0; i < pointCount; i++)
    points.Add(new PointF(1 + R.Next(100), 1 + R.Next(50)));

for (int i = 0; i < lineCount; i++)
    lines.Add(new Point(R.Next(pointCount), R.Next(pointCount)));

现在我们添加点,直截了当:

foreach (PointF pt in points) SP.Points.AddXY(pt.X, pt.Y);

..和线。在这里,我(ab)使用Point结构将两个整数索引存储到points数据中..:

foreach (Point ln in lines)
{
    int p0 = SL.Points.AddXY(points[ln.X].X, points[ln.X].Y);
    int p1 = SL.Points.AddXY(points[ln.Y].X, points[ln.Y].Y);
    SL.Points[p0].Color = Color.Transparent;
    SL.Points[p1].Color = Color.OrangeRed;
}

}

完成。

您可以将LineAnnotations添加到一系列积分中,但这并不是那么简单,我很害怕..

删除一个连接,您可以删除构成该网址的 点:

要删除连接rc,请使用:

chart1.Series[1].Points.RemoveAt(rc * 2);  // remove 1st one
chart1.Series[1].Points.RemoveAt(rc * 2);  // remove 2nd one, now at the same spot