How do I label two vectors in Matlab?

2019-05-18 05:20发布

问题:

I have a 2 column matrix(called M, which I visualize as two vectors using Matlab's plot command(plot(M)). I have two issues:

  1. I want to label the vectors themselves on the plot.
  2. I want to label each row of the matrix(i.e. each vector component) on the plot.

How would I go about doing those things?

回答1:

An example:

M = cumsum(rand(10,2) - 0.5);
x = 1:size(M,1);
plot(x, M(:,1), 'b.-', x, M(:,2), 'g.-')
legend('M1', 'M2')
for i=x
    text(i+0.1, M(i,1), sprintf('%.2f', M(i,1)), 'FontSize',7, 'Color','b');
    text(i+0.1, M(i,2), sprintf('%.2f', M(i,2)), 'FontSize',7, 'Color','g');
end

Alternatively, you can use:

datacursormode()

which will enable the user to just point and click on points to see the data labels.



回答2:

You may need to tweak this to get the positions of the labels exactly how you want them, but something like this will do the trick.

M = [1 2; 3 4; 5 6]
plot(M)
nrows = size(M, 1);
ncols = size(M, 2);
x = repmat(nrows - .3, 1, ncols);
y = M(end, :) - .3;
labels = cellstr([repmat('Col', ncols, 1), num2str((1:ncols)')]);
text(x, y, labels)


回答3:

You can label each axis with the function:

xlabel('label')
ylabel('label')

These can also take cell arguments, where each row is a new line. That's handy for showing units. Labeling each point on the figure can be done as so:

for i=1:length(M)
    text(M(i,1),M(i,2),'Label Text')
end

The label text can also be a string variable that you can edit with sprintf and make special strings for each point.