尝试在matlab中更改与条形图相关的一些属性是非常令人困惑的。我在这里找到了一些解决问题的办法。但是,有一个我找不到。考虑以下情况:
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)]);
这段代码是为了在matlab中生成一个堆叠的条形图而编写的,不是最复杂的解决方案,但它可以工作。我得到的条形图如下:
现在我正试图颠倒我的传奇条目的顺序,使它们与情节相匹配。有些人建议在琴弦上使用flipud或fliplr,但这不起作用。这会更改字符串的顺序,但不会更改颜色。谁能提出一个方法,一个匹配的颜色之间的传奇和情节的顺序?例如,str4应为蓝色
请注意,flipud建议适用于折线图,但不适用于这样的堆叠条形图。使用线图的示例:
x = 1:10;
h = zeros(5, 1);
hold on;
cols = {'r', 'g', 'b', 'y', 'k'};
for k = 1:5
h(k) = plot(x, k*x, cols{k});
end
legend({'one','two','three', 'four', 'five'}) % one way
legend(flipud(h), {'one', 'two', 'three', 'four', 'five'}) % another way
溶液
下面是使用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 is as my code above
for k = (n/2 + 1):n;
a1 = get(ll2(k),'Children');
set(a1,'FaceColor',MAP(k-n/2,:));
end
1条答案
按热度按时间trnvg8h31#
因此,您可以像这样独立于条形图的颜色来控制图例的颜色(请注意,我是基于this post然后通过检查命令行中的对象属性来获得这个想法的):
因此,尝试将
RGBTriple
设置为[1,0,0]
,您应该会看到所有图例框都变成红色。因此,现在只是获取条形图颜色(可能以非常相似的方式)并翻转它们的情况。这里有一个简单的方法来找到正确的颜色:
1.获取当前色彩Map表:
1.将色彩Map表缩小到图例大小:
1.用于RGBTriple: