【发布时间】:2015-07-02 07:21:49
【问题描述】:
试图在 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 应该是蓝色的
请注意,翻转建议适用于线图,但不适用于像这样的堆积条形图。使用线图的示例:
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
【问题讨论】:
-
当我运行你的代码时,我得到了错误:
Error using matlab.graphics.illustration.Legend/setThere is no PlotBoxAspectRatio property on the Legend class.。所以我怀疑这是版本不兼容(我正在运行 2015a),这可能会影响我在下面为您工作的答案。但是试试看。
标签: matlab