Search code examples
c#zedgraph

How to draw a bar curve in zedgraph where the bars are next to each other?


I want to draw a curve out of bars, where the bars start at the lower left corner of (x,0) and go up to (x,y), the width depends on where the next Curve point starts

Given the following points:

X    Y
0    3
1    4
3    2

i want to have bars drawn from

(0,3) to (1,3)
(1,4) to (3,4)
(3,2) to (4,2) 

The width of the last bar could be a constant or 0.

In my test project i used BoxObj objects that I added to the GraphObjListof the GraphPane:

private void Form1_Shown(object sender, EventArgs e)
{
    // Make some sample data points
    PointF[] p = new PointF[360];
    for (int i = 0; i < p.Length; i++)
    {
        p[i] = new PointF(i,(float) Math.Sin(i * (Math.PI *2 )/360));
    }
    // 2 Curves, with different interpolations of their values
    for (int i = 0; i < p.Length; i++)
    {
        // Left point extends to the next point
        ppl.Add(p[i].X, p[i].Y);
        if (i+1 < p.Length)
            ppl.Add(p[i+1].X, p[i].Y);

        // Right point extends to the previous point
        if (i> 0)
            ppl1.Add(p[i- 1].X, p[i].Y);
        ppl1.Add(p[i].X, p[i].Y);
    }
    // Box objects like the curve of ppl, negative values still need to be corrected
    for (int i = 0; i < p.Length-1; i++)
    {
        BoxObj b = new BoxObj(p[i].X, p[i].Y, p[i+1].X-p[i].X, p[i].Y);
        b.IsClippedToChartRect = true;
        b.Fill = new Fill(Brushes.PapayaWhip);
        zedGraphControl1.GraphPane.GraphObjList.Add(b);
    }
    ZedGraph.CurveItem neueKurve = zedGraphControl1.GraphPane.AddCurve("+1",ppl , Color.Blue);
    ZedGraph.CurveItem neueKurve1 = zedGraphControl1.GraphPane.AddCurve("-1",ppl1 , Color.Green);
    ZedGraph.BarSettings bs = new ZedGraph.BarSettings(zedGraphControl1.GraphPane);

    bs.Type = ZedGraph.BarType.Stack;
    zedGraphControl1.GraphPane.AxisChange();
    zedGraphControl1.PerformAutoScale();
    zedGraphControl1.Invalidate();

}

This works, but the box objects are not organized like a CurveItem object.


Solution

  • The solution is very simple, after finding the source code of the zedgraph library I came out with this

    ZedGraph.LineItem neueKurve = new LineItem("+1", ppl, Color.Blue, SymbolType.None);
    ZedGraph.LineItem neueKurve1 = new LineItem("+2", ppl1, Color.Green, SymbolType.None);
    neueKurve.Line.StepType = StepType.ForwardSegment;
    neueKurve.Line.Fill.Type = FillType.Brush;
    neueKurve.Line.Fill.Brush = SystemBrushes.Info;
    neueKurve1.Line.StepType = StepType.RearwardSegment;
    zedGraphControl1.GraphPane.CurveList.Add(neueKurve);
    zedGraphControl1.GraphPane.CurveList.Add(neueKurve1);
    

    Line.StepType = StepType.RearwardSegment; allows to select how the points of the curve are connected.