图表:X标签上的垂直线和字符串

时间:2015-01-05 20:29:22

标签: c# winforms forms charts linechart

我使用WinForms创建折线图。我有两个相关的问题:

  1. 如何在图表上绘制垂直线?

    我试图使用以下方法在(0,0)和(0,5)两点之间画一条垂直线:

    chart1.Series["Pakistan"].Points.AddXY(0, 0);
    chart1.Series["Pakistan"].Points.AddXY(0, 5);
    

    然而,我得到一条从(0,0)到(1,5)的斜线。

  2. 如何在X轴上用字符串标记此行?

2 个答案:

答案 0 :(得分:4)

您可以使用StripLine在x轴上显示垂直线:

StripLine stripLine = new StripLine();
stripLine.Interval = 0; // only show 1 line
stripLine.Offset = 0; // start it at x=0
stripLine.StripWidth = 1; // the width is 1
// set colors, etc
chart1.ChartAreas["Default"].AxisX.StripLines.Add(stripLine);

您还可以创建第二个类型RangeColumn,在每个x值处获取2 y值,以创建垂直线:

Series lineSeries = chart1.Series.Add("line");
lineSeries.ChartType = RangeColumn;
lineSeries.Points.AddXY(0, new []{0, 1});
// Set line widths, colors, etc

最后,您可以处理PostPaint的{​​{1}}事件,使用`Graphics对象绘制一条线:

Chart

处理private void chart1_PostPaint(object sender, ChartPaintEventArgs e) { if(sender is ChartArea) { ChartArea area = (ChartArea)sender; if(area.Name == "Default") { // Get Graphics object from chart Graphics graph = e.ChartGraphics.Graphics; // Convert X and Y values to screen position float pixelYMax = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.Y,1); float pixelXMax = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.X,0); float pixelYMin = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.Y,0); float pixelXMin = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.X,0); PointF point1 = PointF.Empty; PointF point2 = PointF.Empty; // Set Maximum and minimum points point1.X = pixelXMax; point1.Y = pixelYMax; point2.X = pixelXMin; point2.Y = pixelYMin; // Convert relative coordinates to absolute coordinates. point1 = e.ChartGraphics.GetAbsolutePoint(point1); point2 = e.ChartGraphics.GetAbsolutePoint(point2); // Draw connection line graph.DrawLine(new Pen(Color.Yellow,3), point1,point2); } } } 可能是最好的选择,并且可以让您最好地控制线条及其外观。

答案 1 :(得分:2)

Q1。 :在我看来,你遇到了Chart控件中的一个错误。这是解决方法

选择ChartType' Line'和一个很好的线宽:

 chart1.Series["Pakistan"].ChartType = SeriesChartType.Line;
 chart1.Series["Pakistan"].BorderWidth = 2;

在真实数据之前插入虚拟点:

chart1.Series["Pakistan"].Points.AddXY(-1, 0);

现在隐藏第一个真实点之前的线段:

chart1.Series["Pakistan"].Points[1].Color = Color.Transparent;

您可能需要设置显示窗口以排除虚拟..

Axis XA = chart1.ChartAreas[0].AxisX;
XA.Minimum = -1;
XA.Maximum = yourMaximum;

(直到sombody解释它我认为这种行为是一个错误,只发生在X = 0的位置..)

Q2。 :要将字符串作为标签添加到数据点,请使用以下代码。

chart1.Series["Pakistan"].Points[1].AxisLabel = "Label 1";

enter image description here