Reputation: 625
I have the following Bar chart:
Code to create it:
names = {'a', 'b',.....}
b = bar(cell2mat(data_plot'));
legend(b,names,'Location', 'eastoutside');
ylabel('Teest');
So, I want to add a legend to it, but not from each of the bars (blue, yellow, orange) but for the groups of bars(1, 2, 3 ,4 ...)
In names are saved all the names for the 12 groups, but I dont know how to set them as values for the legend. Instead I get other values that are describing each of the bars?
UPDATE: To be more clear, I don't want to change the values on the x-aches (1,2,..) with values from names. I want the (1,2..) to stay where they are and how they are, but instead I want to change the table on the right where I have a legend for the Blue, Orange and Yellow bars with values that would correspond to the (1,2,3..) with the ones from names.
Example: 1 are data from 'USA' so the first value in names is 'USA'. This means on the table on the right I want sth like 1: 'USA'
Upvotes: 2
Views: 674
Reputation: 170
EDIT: Leaving for Legacy's sake. Ignore. I misunderstood the problem and jumped to an answer I thought of instead of taking the time to read and test a solution.
Try set(gca, 'xticklabel', names);
Also be sure to check out the following on why:
Upvotes: -1
Reputation: 13876
You can't do what you want directly, you need to plot each group at a time, see this related post on MATLAB Answers and this question on SO. Here's a workaround based on this, but the bars in each group have to be the same colour:
Y = rand(5,3);
names = {'a';'b';'c';'d';'e'};
colours = {'g';'r';'b';'y';'c'};
h = zeros(size(Y));
for k = 1:size(Y,1)
h(k,:) = bar(3*k-2,Y(k,:),colours{k});
hold on
end
xlim([0 15]);
set(gca,'XTick',[1 4 7 10 13]);
set(gca,'XTickLabel',{'1';'2';'3';'4';'5'});
ylabel('Test');
legend(h(:,1),names,'location','northeastoutside')
which produces the following:
Upvotes: 3