Search code examples
c#zedgraph

ZedGraph Pie Label: How to display Value and Percent, but not Name?


I am using ZedGraph to display some pie charts in my C# WinForms application. I want to display a legend and also the labels next to each pie slice in the following format:

Legend: Each item should display the Name of the pie slice, e.g. "Customers"

Slice Label: Each label should display value and percent, e.g. "4 (25%)"

By default I am able to have the legend displaying the name as desired. So on to the label requirement...

I have looked into the LabelType property, which allows me to select a few options for the label format (here is the list). Unfortunately, there is no Value_Percent option. I cannot use the ones that include the Name because they are too long and it ruins the display of the labels.

I though perhaps I could set the text label myself as I am able to calculate both the Value and Percent anyway, so I tried this:

pieItem.Label.Text = myCustomString;

This does get my desired labels, but it also sets the legend key format to be the same - so I lose that requirement of Name.

Is it possible to change the slice label text independent of the legend text? Or, is it possible to achieve my requirements another way?


Solution

  • I have managed to achieve my requirements by modifying the source code. I would still be interested in knowing if there is a way to do it without making source changes, but in the mean time here is what I did...

    The source code can be downloaded from here, and I used version 5.1.5 so my line number references may be wrong in other versions.

    There are two segments of code that need to be added, in two separate files:

    ZedGraph/Types.cs

    There is an enum called PieLabelType located at line 729. Here we need to add a new value called Value_Percent.

    ZedGraph/PieItem.cs

    There is a function called BuildLabelString located at line 942. Within this function is a switch statement that we need to add a new condition for our new PieLabelType:

    case PieLabelType.Value_Percent:
        curve._labelStr = curve._pieValue.ToString("F", labelFormat) + " (" + (curve._sweepAngle / 360).ToString("P", labelFormat) + ")";
        break;
    

    I have chosen the format "# (#.##%)", obviously this can be anything that is required.

    That's it. Just build the project and then include the new modified DLL in your application and the new PieLabelType will be ready to use.