2017-08-05 53 views
1

考慮下面的例子:MATLAB劇情 - 圖例條目爲多個數據行 - getcolumn

x = magic(3); 
figure(1); clf(1); 
plot(x, '-r', 'DisplayName', 'Magic'); 
legend('show'); 

的在MATLAB 所得圖例條目R2014a
getcolumn(魔術,1)
getcolumn (Magic,2)
getcolumn(Magic,3)

問題從function [leg,labelhandles,outH,outM] = legend(varargin)legend.m版權所有1984年至2012年MathWorks公司),線628莖:
str{k} = get(ch(k),'DisplayName');
更具體地,功能get

  • 預規劃getcolumn(
  • 追加, <Column Number>)

有一種簡單的方法來顯示DisplayName命名的多行數據,它們具有相同的視覺特性正好一個圖例項(或多個,但沒有預先追加字符串)?

當然,另一種方法是通過繪圖手柄以編程方式創建多個(或一個)圖例條目(請參見下文),但我想保持簡短。

一個條目:

x = magic(3); 
figure(1); clf(1); 
h = plot(x, '-r'); 
legend(h(1), 'Magic'); 

多個條目:

x = magic(3); 
figure(1); clf(1); 
h = plot(x, '-r'); 
strL = cell(1, numel(h)); 
for k = 1:numel(h) 
    strL{k} = sprintf('Magic %d', k); 
end 
legend(h, strL); 

在MATLAB R2014b,與getcolumn(名稱,行)的問題不會再出現了第一代碼示例。

回答

1

如果你想在短期語法的圖例條目設置多個顯示名稱,你只需要與他們準備一個單元陣列,讓我們說這就是所謂的leg_names,然後用set將它們應用到所有的一次:

set(p,{'DisplayName'},leg_names); 

讓我們看一個例子:

x = magic(3); % your data 
p = plot(x,'-r'); % plot and get an array of handles to the lines 
% create a list of the desired names for the legend entries: 
leg_names = [repmat('Magic ',size(x,2),1) num2str((1:size(x,2)).')]; 
set(p,{'DisplayName'},cellstr(leg_names)); % set all display names 
legend('show'); % show the legend 

結果是完全按照你的問題的最後例子。

另外,注意語法:[lgd,icons,plots,txt] = legend(___)不推薦(from the docs):

注:不建議使用這種語法。它會創建一個不支持所有圖形功能的圖例。請改用lgd = legend(__)語法來返回圖例對象並設置圖例屬性。