2

How can I add some text on top of a bar in a chart. This is the code I have to add the bar:

var color = ColorTranslator.FromHtml(row.Colour);
var barItem = graphPane.AddBar(row.Propensity.ToString(), null, Ys.ToArray(), color);

Thank you

Lince81
  • 815
  • 5
  • 17
  • 30

3 Answers3

6

Here is a quick example using TextObj to simply add labels to each bar.

GraphPane myPane = zedGraphControl1.GraphPane;

double[] y = { 100, 50, 75, 125 };

BarItem myBar = myPane.AddBar("Data", null, y, Color.Red);
for (int i = 0; i < myBar.Points.Count; i++)
{
    TextObj barLabel = new TextObj(myBar.Points[i].Y.ToString(), myBar.Points[i].X, myBar.Points[i].Y + 5);
    barLabel.FontSpec.Border.IsVisible = false;
    myPane.GraphObjList.Add(barLabel);
}

myBar.Label.IsVisible = true;

zedGraphControl1.AxisChange();
zedGraphControl1.Invalidate();

Bar chart with labels

Of course this just uses the value of the data as the label. If you wanted to use custom labels, you could create a string array or list and use that inside the loop.

Here are some ZedGraph references:

JYelton
  • 35,664
  • 27
  • 132
  • 191
1

You need to define AlignH and AlignV in your text object:

TextObj textLabel = new TextObj(value.ToString(), positionX, value, CoordType.AxisXYScale, AlignH.Center, AlignV.Top);

AlignV define the position of your value on the bar.

edwoollard
  • 12,245
  • 6
  • 43
  • 74
Masa
  • 11
  • 1
0

Providing you want the label text to match the value of each bar, then you can do it with a single line of code:

BarItem.CreateBarLabels(graphPane, false, "F0");

Note that the 3rd parameter is a double.ToString format. e.g. "F0" = 12, "F2" = 12.34

However, if you want any flexibity with it then this solution is not ideal. It also doesn't work very well if you have a stacked bar chart, because having any 0 value data will cause labels to overlap and look horrific

musefan
  • 47,875
  • 21
  • 135
  • 185