2016-07-22 110 views
4

我想繪製一張條形圖,就像下圖所示。MATLAB:如何繪製具有不同比例和不同數據集的多個水平條形圖?

enter image description here

什麼我不能做的就是繪製2組數據,一個上的「0」的左側,並分別在一個在右邊,使用每一個x軸上的不同比例。使用函數barh有關於如何移動基線的說明,但在這種情況下,有兩組具有不同比例的不同數據。

作爲例子,我試圖繪製以下陣列:

left = [.1; .5; .4; .6; .3]; % Scale 0-1, grows leftwards 
right = [24; 17; 41; 25; 34]; % Scale 0-35, grows rightwards 

任何提示嗎?

回答

3

要處理不同的縮放比例,您可以手動乘以left中的值進行縮放,然後修改該邊的刻度線。

% Automatically determine the scaling factor using the data itself 
scale = max(right)/max(left); 

% Create the left bar by scaling the magnitude 
barh(1:numel(left), -left * scale, 'r'); 

hold on 
barh(1:numel(right), right, 'b')  

% Now alter the ticks. 
xticks = get(gca, 'xtick') 

% Get the current labels 
labels = get(gca, 'xtickLabel'); 

if ischar(labels); 
    labels = cellstr(labels); 
end 

% Figure out which ones we need to change 
toscale = xticks < 0; 

% Replace the text for the ones < 0 
labels(toscale) = arrayfun(@(x)sprintf('%0.2f', x), ... 
          abs(xticks(toscale)/scale), 'uniformoutput', false); 

% Update the tick locations and the labels 
set(gca, 'xtick', xticks, 'xticklabel', labels) 

% Now add a different label for each side of the x axis 
xmax = max(get(gca, 'xlim')); 
label(1) = text(xmax/2, 0, 'Right Label'); 
label(2) = text(-xmax/ 2, 0, 'Left Label'); 

set(label, 'HorizontalAlignment', 'center', 'FontWeight', 'bold', 'FontSize', 15) 

enter image description here

+0

非常感謝,這看起來幾乎等同於一個在例子!如果你不介意,我還有兩個問題可以使它更加相似。由於我只使用正值,你會知道是否有兩種方法獲得正值:另外,您是否知道是否可以在x軸上添加兩個單獨的標籤,每個數據集都有一個標籤? –

+0

@ Giovanni.R88更新 – Suever

+0

太棒了!非常感謝! –

3

下面是一個例子:

left = [.1; .5; .4; .6; .3]; % Scale 0-1, grows leftwards 
right = [24; 17; 41; 25; 34]; % Scale 0-35, grows rightwards 

ax_front = axes; 
b_front = barh(right,0.35); 
set(b_front,'facecolor',[0.2,0.4,1]) 
axis([-50,50,0,6]) 
axis off 

ax_back = axes; 
b_back = barh(-left,0.35) 
axis([-1,1,0,6]) 
set(b_back,'facecolor',[1,0.4,0.2]) 
set(gca, 'xtick', [-1:0.2:1]) 
set(gca, 'xticklabel', [[1:-0.2:0],[10:10:50]]) 
grid on 

axes(ax_front) % bring back to front 

結果:

enter image description here

相關問題