MATLAB:如何绘制具有不同比例和不同数据集的多个水平条形图?

5
我想画一张与下图完全相同的条形图。

enter image description here

我无法做到的是绘制两组数据,一组位于“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

任何提示吗?
2个回答

4
为了处理不同的缩放,您可以手动将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


非常感谢,这看起来几乎与示例中的相同!如果您不介意,我有两个进一步的问题,以使它更相似。由于我仅使用正值,您是否知道是否有一种方法可以在两个轴上获得正比例尺?此外,您是否知道是否可以在x轴上添加两个单独的标签,每组数据一个? - Giovanni.R88
@Giovanni.R88 已更新 - Suever

4

以下是一个示例:

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

结果:

在此输入图片描述


(注:该内容为HTML代码,已翻译成中文)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接