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

Matlab 2016b中绘制可变宽度条形图的技术实现咨询

Solution for Custom Bar Chart with Variable Widths, Height, and Color Coding in MATLAB

Ah, I feel your pain—the built-in bar function is great for standard bar charts, but it falls short when you need per-bar customization like variable widths. The workaround here is to use rectangle objects instead, which let you control each "bar's" position, width, height, and color individually.

Here's a complete, actionable implementation:

Step 1: Prepare Your Data (Example Structure)

First, let's assume your data is structured like this (adjust to match your actual data format):

% Sample dataset (replace with your real data)
data = struct();
data.type = {'Control', 'Treatment', 'Control', 'Placebo'};
data.duration = [2.5, 1.8, 3.2, 2.1];  % Width of each bar (X-axis units)
data.avg = [6.2, 8.1, 5.7, 7.3];      % Height of each bar (Y-axis value)

Step 2: Calculate Bar Positions

Since each bar has a unique width, we need to calculate where each one starts on the X-axis. For a contiguous layout (no gaps between bars):

% Compute starting X coordinates for each bar
x_start = zeros(size(data.duration));
x_start(1) = 0;
for i = 2:length(x_start)
    x_start(i) = x_start(i-1) + data.duration(i-1);
end

If you want gaps between bars, just add a small offset (e.g., x_start(i) = x_start(i-1) + data.duration(i-1) + 0.3;)

Step 3: Define Color Mapping for Types

Map each type to a unique color for easy visual distinction:

% Create a color map for your types (customize these RGB values as needed)
color_map = containers.Map(...
    {'Control', 'Treatment', 'Placebo'}, ...
    {[0.2 0.4 0.8], [0.8 0.2 0.2], [0.2 0.8 0.4]} ...
);

Step 4: Draw Each Bar as a Rectangle

Loop through your data to create individual rectangle objects (each acting as a custom bar):

figure; hold on; axis tight;

for i = 1:length(data.duration)
    % Rectangle position format: [x_start, y_bottom, width, height]
    rectangle(...
        'Position', [x_start(i), 0, data.duration(i), data.avg(i)], ...
        'FaceColor', color_map(data.type{i}), ...
        'EdgeColor', 'black',  % Optional: adds sharp borders to bars
        'LineWidth', 0.5       % Optional: adjust border thickness
    );
end

Step 5: Customize Axes and Legend

Finish by adding labels, a title, and a legend to make the chart clear:

% Axis labels and title
xlabel('Cumulative Duration', 'FontSize', 12);
ylabel('Average Value', 'FontSize', 12);
title('Custom Bar Chart: Variable Width, Height, and Type Color Coding', 'FontSize', 14);

% Create legend entries (since we used rectangles, we need dummy objects for the legend)
unique_types = unique(data.type);
legend_handles = [];
legend_labels = [];

for t = unique_types
    legend_handles = [legend_handles, rectangle('FaceColor', color_map{t{1}}, 'EdgeColor', 'black')];
    legend_labels = [legend_labels, t{1}];
end

legend(legend_handles, legend_labels, 'Location', 'best');

% Add padding to the Y-axis so bars don't touch the top
ylim([0, max(data.avg) * 1.1]);

hold off;

Why This Works

Unlike bar, which renders bars as a single group object, each rectangle is an independent graphic object. This means you can tweak every parameter (width, color, position) for each bar individually—exactly what you need for your use case.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:56:44