Search code examples
matlabmatlab-figureinterpreter

MATLAB pie labels turn off interpreter


I want to plot a pie from a string vector that I get from another function. These strings include _ symbols and the labels use the default interpreter and show special symbols instead of the original strings. How can I turn off the interpreter there? (I tried some commands such as set(Groot, 'defaultLegendInterpreter', 'none') and pie(categorical(str_vec),' Interpreter',' none') but nothing was good.)

str_vec = ["a_l" "a_l" "ab" "ab" "c_m"];
figure;pie(categorical(str_vec))

pie


Solution

  • You can explore the pie function with edit pie, and with a little digging we can see that each pie "slice" is created as a patch object, and each label is created as a text object. Notably, the text object creation only uses the following properties:

    text(xtext,ytext,labels{i},...
      'HorizontalAlignment',halign,'VerticalAlignment',valign,...
      'Parent',cax,'Layer','front');
    

    i.e. it doesn't set the Interpreter property, which is 'tex' by default. This means we're not going to be able to set it while calling the pie function and will have to do it after the chart creation.

    You can set all of the text objects' interpreter to 'none' using

    % Assign output objects to variable 'p', inc. the text labels
    p = pie(categorical(str_vec)); 
    % Get the text objects from the pie chart
    labels = p( arrayfun( @(x) isa(x,'matlab.graphics.primitive.Text'), p ) );
    % Set their interpreter
    set( labels , 'Interpreter', 'none' );
    

    If you're not familiar with arrayfun which I'm using to condense things here, you can do the same thing with a loop

    p = pie(categorical(str_vec)); 
    for ii = 1:numel(p)
        if isa(p(ii),'matlab.graphics.primitive.Text')
            set( p(ii), 'Interpreter', 'none' );
        end
    end
    

    Output:

    plot