Search code examples
matlabmatlab-figuresuperscript

Matlab Superscripts in fitlm figure title


I am conducting some linear modelling and plotting the output. I wish to include the r^2 value in the title title doc, but with the 2 as a superscript.

For some reason, the line of code from the documentation isn't producing the title as desired when plotting the linear model output fitlm doc. How to solve this?

clear
clc

%Make test data
%----------------------------
x1 = 1:0.01:3;
r = -1 + (1+1)*rand(1,201);
x1 = x1 + r;

y1 = 1:0.01:3;
r = -1 + (1+1)*rand(1,201);
y1 = y1 + r;

x1 = x1';
y1 = y1';
label1 = zeros(length(y1),1);

Tclust1 = [label1,x1,y1];
%----------------------------
x2 = 4:0.01:6;
r = -1 + (1+1)*rand(1,201);
x2 = x2 + r;

y2 = 10:0.01:12;
r = -1 + (1+1)*rand(1,201);
y2 = y2 + r;

x2 = x2';
y2 = y2';
label2 = ones(length(y2),1);

Tclust2 = [label2,x2,y2];

%----------------------------
x3 = 5:0.01:7;
r = -1 + (1+1)*rand(1,201);
x3 = x3 + r;

y3 = 11:0.01:13;
r = -1 + (1+1)*rand(1,201);
y3 = y3 + r;

x3 = x3';
y3 = y3';
label3 = label2+1;

Tclust3 = [label3,x3,y3];
%----------------------------
T = [Tclust1;Tclust2;Tclust3];

%Prep for LM -------------------------------------------------------------
%Classify by labels
Label_idx = zeros(length(T(:,1)),1);

for qq = 1:length(Label_idx)  
    if T(qq,1) > 0
        Label_idx(qq) = 1;
    end
end

for qq = 1:length(Label_idx)
    if T(qq,1) > 1
        Label_idx(qq) = 2;
    end
end

%dummy variables
for qq = 1:length(Label_idx)
    if Label_idx(qq) == 0
        Label_1(qq) = 1;
    else
    Label_1(qq) = 0;
    end
end

Label_1 = Label_1';

for qq = 1:length(Label_idx)
    if Label_idx(qq) == 2
        Label_2(qq) = 1;
    else
    Label_2(qq) = 0;
    end
end

Label_2 = Label_2';

%Do the Linear modelling -------------------------------------------------

%Input predictor
pred = (T(:,2));
%Input comparator
comp = (T(:,3));

%interaction parameters
int_lo = pred.*Label_1;
int_hi = pred.*Label_2;

%predictors
    X = [pred,Label_1,Label_2,int_lo,int_hi];
    LR_mdl = fitlm(X,comp);

%plot ==========================================================
plot(LR_mdl)
arrayfun( @(x) set(x,'DisplayName',strrep(x.DisplayName,'*',' × ')), findall(gcf,'type','line') )
% title('title^2')
% title('^{super} normal _{sub}')
title('text ^{superscript} ')

figure(2)
scatter(x1,y1)
title('text ^{superscript} ')
`

Note, the line of code does produce a desired superscripts for figure 2, when only plotting some of the raw data, not the linear model.


Solution

  • You need to change the Interpreter of the title.

    title('text ^{superscript} ', 'Interpreter', 'Tex')
    

    From the documentation, Tex is the default for normal plots, presumably this is altered by the plot function for a linear regression model, but you can override it as above regardless.