【问题标题】:MATLAB: How to draw a multiple horizontal bar plot with different scales and different sets of data?MATLAB:如何绘制具有不同比例和不同数据集的多水平条形图?
【发布时间】:2016-11-26 06:26:16
【问题描述】:

我想绘制一个与下图中的 on 完全相同的条形图。

我不能做的是绘制两组数据,一组在“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

有什么提示吗?

【问题讨论】:

    标签: matlab plot bar-chart matlab-figure


    【解决方案1】:

    要处理不同的缩放比例,您可以手动将要缩放的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) 
    

    【讨论】:

    • 非常感谢,这看起来与示例中的几乎一模一样!如果你不介意的话,我还有两个问题要让它更加相似。由于我只使用正值,您是否知道是否有办法在两个轴上获得正比例?另外,您知道是否可以在 x 轴上添加两个单独的标签,每组数据一个标签?
    • @Giovanni.R88 更新
    【解决方案2】:

    这是一个例子:

    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
    

    结果:

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 2021-03-11
      • 1970-01-01
      • 2013-04-29
      相关资源
      最近更新 更多