Main Content

Label Pie Chart With Text and Percentages

When you create a pie chart, MATLAB labels each pie slice with the percentage of the whole that slice represents. You can change the labels to show different text.

Simple Text Labels

Create a pie chart with simple text labels.

x = [1,2,3];
pie(x,{'Item A','Item B','Item C'})

Labels with Percentages and Text

Create a pie chart with labels that contain custom text and the precalculated percent values for each slice.

Create the pie chart and specify an output argument, p, to contain the text and patch objects created by the pie function. The pie function creates one text object and one patch object for each pie slice.

x = [1,2,3];
p = pie(x);

Get the percent contributions for each pie slice from the String properties of the text objects.Then, specify the text that you want in the cell array txt. Concatenate the text with the associated percent values in the cell array combinedtxt.

pText = findobj(p,'Type','text');
percentValues = get(pText,'String'); 
txt = {'Item A: ';'Item B: ';'Item C: '}; 
combinedtxt = strcat(txt,percentValues); 

Change the labels by setting the String properties of the text objects to combinedtxt.

pText(1).String = combinedtxt(1);
pText(2).String = combinedtxt(2);
pText(3).String = combinedtxt(3);

See Also

| |

Related Topics