带2个y轴的分组条形图显示为堆叠条形图

时间:2019-12-18 18:32:31

标签: matlab plot bar-chart

我想绘制分组的条形图以比较三种方法。我尝试了以下代码,它显示为堆积的条形图。请您帮忙

dice =[0, 3, 5];
no_of_region=[42, 12, 5];
figure;
bar(dice',.2,'grouped','FaceColor',[0 .5 .5],'EdgeColor',[0 .9 .9],'LineWidth',1.5)
ylabel('Dice Similarity index')  
yyaxis right
bar(no_of_region, .2,'grouped','EdgeColor', 'r', 'LineWidth', 2);
legend('Dice Similarity Index','Number of regions')
legend('Location','northwest')
XTickLabel={'a' ; 'b';'c'};
XTick=[1 2 3]
set(gca, 'XTick',XTick);
set(gca, 'XTickLabel', XTickLabel);
set(gca, 'XTickLabelRotation', 45);
xlabel('Different Methods', 'Fontsize', 16)
ylabel('Number of Regions', 'Fontsize', 16)
title('Comparison of Algorithms', 'fontsize', 20);
set(gcf,'color','w');

我的输出为: enter image description here

1 个答案:

答案 0 :(得分:0)

一种简单的解决方案是将条形图左右移动一半(如果需要,可以在它们之间留出更多空间)。这是新代码,在样式上也进行了一些清理:

% parameters
dice = [0, 3, 5];
no_of_region = [42, 12, 5];
X = [1, 2, 3]; % common x values for plot
bar_width = 0.2; % width of bars

% initialize figure
figure;

% left plot
bar(X.' - bar_width/2, dice', bar_width, 'grouped', ...
    'FaceColor', [0 .5 .5], ...
    'EdgeColor', [0 .9 .9], ...
    'LineWidth', 1.5);
ylabel('Dice Similarity index');

% right plot
yyaxis right;
bar(X.' + bar_width/2, no_of_region, bar_width, 'grouped', ...
    'EdgeColor', 'r', ...
    'LineWidth', 2);

% plot formatting
legend({'Dice Similarity Index', 'Number of regions'}, ...
    'Location', 'northwest');
XTickLabel = {'a' ; 'b'; 'c'};
XTick = X;
set(gca, ...
    'XTick', XTick, ...
    'XTickLabel', XTickLabel, ...
    'XTickLabelRotation', 45);
xlabel('Different Methods', 'FontSize', 16);
ylabel('Number of Regions', 'FontSize', 16);
title('Comparison of Algorithms', 'FontSize', 20);
set(gcf, 'color', 'w');

根据期望的行为,您还可以考虑将figure;替换为clf;,这将清除现有图形或打开新图形窗口(如果尚未打开)。