Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Put String Labels on Contours for Contour Plots in MATLAB

I am wondering if it is possible to label the contours of a MATLAB contour plot with a set of user-defined strings?

I am currently using the following code snipper to produce a labelled contour plot:

%Create Data
X = 0.01:0.01:0.10
Y = 0.01:0.01:0.10
Z = repmat(X.^2,length(X),1) + repmat(Y.^2,length(Y),1)';

%Create Plot 
hold on
[C,h] = contourf(X,Y,Z);

%Add + Format Labels to Plot
hcl = clabel(C,h,'FontSize',10,'Color','k','Rotation',0);
set(hcl,'BackgroundColor',[1 1 1],'EdgeColor',[0 0 0],'LineStyle','-',)
hold off

The issue with this code is that the labels are automatically generated by MATLAB. Even as I can easily change the contours that are labels, I cannot change the labels that they get.

Ideally, I would like to label them with a set of strings that I define myself. However if that is not possible, then I am wondering if it is possible to change the numeric format of the labels. The reason for this is that the code above actually produce a contour plot for an error rate, which I would like to display as a % value (i.e. use 1% in the contour label, instead of 0.01 etc.).

like image 633
Berk U. Avatar asked Oct 04 '22 01:10

Berk U.


1 Answers

In this case, hcl is actually an array which stores handles to every contour label on your plot. When you set properties using the array (as in your code),

set(hcl, 'name', 'value')

You will set the property of every label to the same value.

You can change the properties of individual labels by iterating over the array. For example, this is how you would add a percentage sign:

for i = 1:length(hcl)
    oldLabelText = get(hcl(i), 'String');
    percentage = str2double(oldLabelText)*100;
    newLabelText = [num2str(percentage) ' %'];
    set(hcl(i), 'String', newLabelText);
end
like image 122
Huguenot Avatar answered Oct 13 '22 10:10

Huguenot