matlab条形图中图例颜色的逆序

pxy2qtax  于 2023-10-23  发布在  Matlab
关注(0)|答案(1)|浏览(200)

尝试在matlab中更改与条形图相关的一些属性是非常令人困惑的。我在这里找到了一些解决问题的办法。但是,有一个我找不到。考虑以下情况:

  1. ax1 = subplot(121);
  2. id2 = [8;2;3;5];
  3. id2_t = sum(id2);
  4. id3 = (id2/id2_t).*100; id3(:,2) = 0;
  5. H1 = bar(id3','stacked','EdgeColor','none');
  6. set(gca,'XTicklabel',[]);
  7. xlim([0.75 1.25]);
  8. % add legend
  9. str = {'str1','str2','str3','str4'};
  10. ll = legend(str);
  11. legend('boxoff');
  12. set(ll,'PlotBoxAspectRatio',[0.5 1 1]);
  13. ll_i = get(ll,'position');
  14. set(ll, 'Position', [0.25 ll_i(2)-0.1 ll_i(3) ll_i(4)]);
  15. % change dimensions of plot
  16. AX1 = get(ax1,'position');
  17. set(ax1,'position',[AX1(1) AX1(2) AX1(3)/2.7 AX1(4)]);

这段代码是为了在matlab中生成一个堆叠的条形图而编写的,不是最复杂的解决方案,但它可以工作。我得到的条形图如下:

现在我正试图颠倒我的传奇条目的顺序,使它们与情节相匹配。有些人建议在琴弦上使用flipud或fliplr,但这不起作用。这会更改字符串的顺序,但不会更改颜色。谁能提出一个方法,一个匹配的颜色之间的传奇和情节的顺序?例如,str4应为蓝色
请注意,flipud建议适用于折线图,但不适用于这样的堆叠条形图。使用线图的示例:

  1. x = 1:10;
  2. h = zeros(5, 1);
  3. hold on;
  4. cols = {'r', 'g', 'b', 'y', 'k'};
  5. for k = 1:5
  6. h(k) = plot(x, k*x, cols{k});
  7. end
  8. legend({'one','two','three', 'four', 'five'}) % one way
  9. legend(flipud(h), {'one', 'two', 'three', 'four', 'five'}) % another way

溶液
下面是使用Dan提供的答案的解决方案:

  1. ax1 = subplot(121);
  2. id2 = [8;2;3;5];
  3. id2_t = sum(id2);
  4. id3 = (id2/id2_t).*100; id3(:,2) = 0;
  5. H1 = bar(id3','stacked','EdgeColor','none');
  6. set(gca,'XTicklabel',[]);
  7. xlim([0.75 1.25]);
  8. % add legend
  9. str = {'str1','str2','str3','str4'};
  10. [ll ll2]= legend(str);
  11. legend('boxoff');
  12. set(ll,'PlotBoxAspectRatio',[0.5 1 1]);
  13. ll_i = get(ll,'position');
  14. set(ll, 'Position', [0.25 ll_i(2)-0.1 ll_i(3) ll_i(4)]);
  15. % change dimensions of plot
  16. AX1 = get(ax1,'position');
  17. set(ax1,'position',[AX1(1) AX1(2) AX1(3)/2.7 AX1(4)]);
  18. map = colormap;
  19. n = size(ll2,1);
  20. MAP = map(linspace(size(map,1),1,n/2),:); %// n is as my code above
  21. for k = (n/2 + 1):n;
  22. a1 = get(ll2(k),'Children');
  23. set(a1,'FaceColor',MAP(k-n/2,:));
  24. end

trnvg8h3

trnvg8h31#

因此,您可以像这样独立于条形图的颜色来控制图例的颜色(请注意,我是基于this post然后通过检查命令行中的对象属性来获得这个想法的):

  1. [ll, ll2] = legend(str);
  2. n = size(ll2,1);
  3. for k = (n/2 + 1):n
  4. ll2(k).Children.FaceColor = RGBTriple;
  5. end

因此,尝试将RGBTriple设置为[1,0,0],您应该会看到所有图例框都变成红色。因此,现在只是获取条形图颜色(可能以非常相似的方式)并翻转它们的情况。
这里有一个简单的方法来找到正确的颜色:
1.获取当前色彩Map表:

  1. map = colormap;

1.将色彩Map表缩小到图例大小:

  1. MAP = map(linspace(size(map,1),1,n/2),:); %// n is as my code above

1.用于RGBTriple:

  1. for k = (n/2 + 1):n
  2. ll2(k).Children.FaceColor = MAP(k-n/2,:);
  3. end
展开查看全部

相关问题