reverse ordering of legend colors in matlab bar plot -
trying change of properties associated bar plot in matlab confusing. have found number of solution problems here. however, there 1 cannot find. consider following:
ax1 = subplot(121); id2 = [8;2;3;5]; id2_t = sum(id2); id3 = (id2/id2_t).*100; id3(:,2) = 0; h1 = bar(id3','stacked','edgecolor','none'); set(gca,'xticklabel',[]); xlim([0.75 1.25]); % add legend str = {'str1','str2','str3','str4'}; ll = legend(str); legend('boxoff'); set(ll,'plotboxaspectratio',[0.5 1 1]); ll_i = get(ll,'position'); set(ll, 'position', [0.25 ll_i(2)-0.1 ll_i(3) ll_i(4)]); % change dimensions of plot ax1 = get(ax1,'position'); set(ax1,'position',[ax1(1) ax1(2) ax1(3)/2.7 ax1(4)]);
this code written produce single stacked bar in matlab, not sophisticated of solutions, works. bar plot below:
now trying reverse order of legend entries match plot. people have suggested flipud or fliplr on strings, doesnt work. changes sequence of strings not change colors. can suggest method match ordering of colors between legend , plot? example, str4 should blue
note flipud suggestion works line plots, not stacked bar plot this. example using line plot:
x = 1:10; h = zeros(5, 1); hold on; cols = {'r', 'g', 'b', 'y', 'k'}; k = 1:5 h(k) = plot(x, k*x, cols{k}); end legend({'one','two','three', 'four', 'five'}) % 1 way legend(flipud(h), {'one', 'two', 'three', 'four', 'five'}) % way
solution
here solution using answer provided dan:
ax1 = subplot(121); id2 = [8;2;3;5]; id2_t = sum(id2); id3 = (id2/id2_t).*100; id3(:,2) = 0; h1 = bar(id3','stacked','edgecolor','none'); set(gca,'xticklabel',[]); xlim([0.75 1.25]); % add legend str = {'str1','str2','str3','str4'}; [ll ll2]= legend(str); legend('boxoff'); set(ll,'plotboxaspectratio',[0.5 1 1]); ll_i = get(ll,'position'); set(ll, 'position', [0.25 ll_i(2)-0.1 ll_i(3) ll_i(4)]); % change dimensions of plot ax1 = get(ax1,'position'); set(ax1,'position',[ax1(1) ax1(2) ax1(3)/2.7 ax1(4)]); map = colormap; n = size(ll2,1); map = map(linspace(size(map,1),1,n/2),:); %// n code above k = (n/2 + 1):n; a1 = get(ll2(k),'children'); set(a1,'facecolor',map(k-n/2,:)); end
so can control colours of legend independently of colors of bar chart (note got idea based on this post , inspecting object properties in command line):
[ll, ll2] = legend(str); n = size(ll2,1); k = (n/2 + 1):n ll2(k).children.facecolor = rgbtriple; end
so try setting rgbtriple
[1,0,0]
, should see legend boxes become red. it's case of getting bar chart colors (probably in similar manner) , flipping them.
ok here hacky way find right colors:
get current colormap:
map = colormap;
reduce colormap size of legend:
map = map(linspace(size(map,1),1,n/2),:); %// n code above
use rgbtriple:
for k = (n/2 + 1):n ll2(k).children.facecolor = map(k-n/2,:); end
Comments
Post a Comment