Search code examples
c#histogramzedgraph

Trying to create a histogram with ZedGraph


I am trying to create a histogram with ZedGraph.

The bars and data are all good, the only thing needed is my bars to be between the tics instead of directly on the tics.

Sample data:

1, 4
2, 8
3, 1

Means that I have:

4 items that are >= 0 and < 1
8 items that are >= 1 and < 2
1 item that is >= 2 and < 3

So currently my bars are of course appearing directly on the tics (x values) 1, 2 and 3.

But I would like to see:

  • the first bar between the tics 0 and 1,
  • the second bar between the tics 1 and 2 and
  • the third bar between the tics 2 and 3

What is the property to tweak in order to achieve that? I am currently looking in XAxis and XAxis.Scale, but I haven't found anything yet...


Solution

  • You probably can't do it with normal BarItem. I use the BoxObj objects to create the histogram.

    If histList is the PointPairList containing your pairs of histogram values (breakpoint and value) you can use:

    for (int i = 0; i < histList.Count - 1; i++)
    {
    BoxObj box = new BoxObj(histList[i].X, histList[i].Y, histList[i + 1].X - histList[i].X, histList[i].Y);
    box.IsClippedToChartRect = true;
    box.Fill.Color = myColor;
    pane.GraphObjList.Add(box);
    }
    

    Using the BoxObj you have full control on where the bar is located etc. More info in documentation

    EDIT
    Remember that when using BoxObj (or any GraphObj in general) the X and Y scales are not going to be set automatically. You need to set the scale ranges manually:

    pane.XAxis.Scale.Min = ...
    pane.XAxis.Scale.Max = ...
    pane.YAxis.Scale.Min = ...
    pane.YAxis.Scale.Max = ...