How to draw a Line only between specific points in the same Chart series

别说谁变了你拦得住时间么 提交于 2019-12-11 12:51:02

问题


I have the following issue:

  • A distribution of points plotted on a dot chart;
  • Some of those points need to be connected to each other in a way that a single point could be connected to several different points;
  • Those points need to be connected with a line;
  • Not all points could be connected.

回答1:


One Series can either be of type Point or Line, so we will need to either use two Series or resort to some tricks.

I suggest using two Series, as it is rather simple to code and maintain..

This screenshot shows 100 random points and 25 random connections between them.

A Line chart can only draw one line, connecting all its points, one after the other. So the trick is to add two points per conncection to the Line Series, alternating their Colors between invisible and some visible Color..:

First we set up the Chart with its two Series and a nice 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";

Now we create some random data; you will have to adapt to your data source..:

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)));

Now we add the points, straightforward:

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

..and the lines. Here I (ab)use a Point structure to simply store the two integer indices into the points data..:

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;
}

}

Done.

You could instead add LineAnnotations to one Series of Points, but that's not so simple, I'm afraid..

To remove a connection you would remove both points that make it up:

To remove connection rc use:

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


来源:https://stackoverflow.com/questions/32002464/how-to-draw-a-line-only-between-specific-points-in-the-same-chart-series

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!