Hey John,
You can set the barwidth property when calling the bar function itself. This will ensure that you can set the width to an aboslute value that you specify for any bar graph you want to plot.
The following example shows how you can plot two bar graphs behind a plot, with each bar graph having different barwidth values:
% Parameters for the sine wave
frequency = 1; % Frequency in Hz
amplitude = 1; % Amplitude of the sine wave
phase = 0; % Phase shift
fs = 100; % Sampling frequency
t = 0:1/fs:2*pi; % Time vector
% Generate the sine wave
sine_wave = amplitude * sin(2 * pi * frequency * t + phase);
% Calculate the absolute value of the amplitude
abs_amplitude = abs(sine_wave);
%% We calculate the amplitude value in discrete time segment to create bar graph
% Determine the number of samples per quarter cycle
samples_per_cycle = fs / frequency;
samples_per_quarter = samples_per_cycle / 4;
% Calculate average absolute amplitude for each quarter cycle
quarter_averages = [];
for i = 1:samples_per_quarter:length(abs_amplitude)
% Get the segment of the current quarter
segment = abs_amplitude(i:min(i+samples_per_quarter-1, end));
% Calculate the average of the segment
quarter_averages(end+1) = mean(segment);
end
% creating another array for 2nd bar graph with values that are 20% higher
quarter_averages_2 = quarter_averages * 1.2;
% Create a time vector for the discrete quarters
quarter_times = linspace(0, 2*pi, length(quarter_averages));
%% Plotting the sine wave and the bar graphs
figure;
% Plot the bar graph of the average absolute amplitude for each quarter
bar(quarter_times, quarter_averages, 'BarWidth', 1, 'FaceColor', [1 0 0], 'EdgeColor', 'black');
hold on;
bar(quarter_times, quarter_averages_2, 'BarWidth', 0.5, 'FaceColor', [0 1 0], 'EdgeColor', 'black');
% Plot the sine wave
plot(t, sine_wave, 'b', 'LineWidth', 2);
% Set plot labels and title
xlabel('Time (s)');
ylabel('Amplitude');
title('Sine Wave with Discrete Average Absolute Amplitude Bar Graph');
% Adjust plot limits
xlim([0 2*pi]);
ylim([-1.5 1.5]);
% Display grid
grid on;
% Hold off to stop adding to the current plot
hold off;
In the graph, you can see that the red bar graph width is wider than the green bar graph width.