You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab分组条形图X轴刻度自定义及Y轴值修改技术问询

Solution for Your Grouped Bar Plot Modifications

Let's tackle your two requirements step by step, with a complete modified code and clear explanations:

Modified Full Code

% Original data - handle NaN replacement first
y = [200 200 200 192 160 128 96 64 48 32 96 64 24 48 32; 
     48 64 96 48 32 24 24 64 16 24 48 32 48 64 24; 
     6 6 2 4 4 6 12 8 2 4 8 6 16 12 6; ];

% Requirement 2: Replace all 200 values with NaN
y(y == 200) = NaN;

[rows,cols] = size(y);
n = NaN(rows,cols);
bh = cell(rows,1);
lh = cell(rows,1);
hold on;
for k = 1:rows
    curr = n;
    curr(k,:) = y(k,:);
    bar1 = bar(curr,'FaceColor',rand(1,3));
    bh{k} = bar1;
    lh{k} = bar1(1);
end
hold off;

% Requirement 1: Add specific numbers below each bar
% Define your custom numbers here (example uses y-values; replace with your own set if needed)
specific_nums = y;
% Adjust vertical position for text (tune based on your plot's scale)
text_y_pos = -10;

% Loop through every bar to add text
for k = 1:rows
    for idx = 1:cols
        bar_x = bh{k}(idx).XData;
        display_num = specific_nums(k,idx);
        % Skip NaN values since those bars don't exist
        if ~isnan(display_num)
            text(bar_x, text_y_pos, num2str(display_num), ...
                'HorizontalAlignment','center', ...
                'FontSize',10, ...
                'FontWeight','normal');
        end
    end
end

% Keep your original labels and legend
legend([lh{:}],{'1st group','2nd group', '3rd group'},...
    'fontweight','bold','Location','best','FontSize',12);
xlabel('Samples (45 Locations) ','fontweight','bold','FontSize',12);
ylabel('Distance Error (meters)','fontweight','bold','FontSize',12);
% Adjust y-axis limits to prevent text from being cut off
ylim([text_y_pos-5 max(y(:),[],'omitnan')+10]);

Key Breakdown of Changes

1. Replacing 200 with NaN

  • We use logical indexing y(y == 200) = NaN; to target every element equal to 200 and swap it with NaN in a single line. This ensures those positions won't render any bars in your plot.

2. Adding Specific Numbers Below Bars

  • First, set up your specific_nums array: this can be the original y-values (as shown) or any custom set of numbers you need to display (just make sure it matches the rows x cols size of your data).
  • We loop through each bar in every group, fetch its x-position using bar.XData, then use the text() function to place the number below the bar.
  • We skip NaN values since those bars don't exist, so no text is needed for them.
  • The ylim() adjustment ensures the text below the x-axis isn't cut off — feel free to tweak text_y_pos and the y-limits to fit your plot's scale.

内容的提问来源于stack exchange,提问作者Mohsen Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:15:11