【问题标题】:grouped bar chart with 2 y-axes is displayed as stacked bar具有 2 个 y 轴的分组条形图显示为堆叠条形图
【发布时间】:2019-12-18 18:32:31
【问题描述】:

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

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');

我得到的输出:

【问题讨论】:

  • 这些条实际上并没有堆叠,也就是说,当一个条从前一个结束的地方开始时。在您的情况下,它们被绘制在彼此之上,完全覆盖了较小的条。我猜您希望这些条彼此相邻,向左或向右偏移一点?
  • 如何设置偏移量?
  • hb=bar(no_of_region,.2,'stacked','EdgeColor', 'r', 'LineWidth', 2);对于 ib = 1:numel(hb) %XData 属性是刻度标签/组中心; XOffset 是每个不同组的偏移量% xData = hb(ib).XData+hb(ib).XOffset;结束没有工作

标签: matlab plot bar-chart


【解决方案1】:

一个简单的解决方案是将条形左右移动一半宽度(如果您希望它们之间有空间,则可以更多)。这是新代码,在风格上也进行了一些清理:

% 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;,这会清除现有图窗或打开一个新图窗窗口(如果尚未打开)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多