Reputation: 11
I am attempting to populate a legend of a bar graph for the corresponding number of quantities being plotted, which is variable. I have included a typical legend's plotting scheme below, though I am attempting to replicate this for a variable number of elements in the vector 'test'. I understand that this is relatively simple procedure, but my experience is limited and any help would be appreciated.
test=[1,2,3,4,5]
bar(diag(test), 'stacked')
legend('label1','label2','label3','label4','label5');
xlabel('labels')
title('Title')
Upvotes: 1
Views: 39
Reputation: 337
You can combine the labels in one array. That way you would be able to work with a dynamic number of labels.
This does the same thing with your code, but the legend function is called with an array:
test=[1,2,3,4,5]
bar(diag(test), 'stacked')
legend(["label1", "label2", "label3", "label4", "label5"]);
xlabel('labels')
title('Title')
Note that I used strings (") instead of chars (') because char arrays are harder to operate as arrays.
You can also automate the names completely,
test=[1,2,3,4,5]
bar(diag(test), 'stacked')
legendNames = "label" + test;
legend(legendNames);
xlabel('labels')
title('Title')
Upvotes: 1