bar plot with two y-axis padding with zeros in matlab

To create a bar plot with two y-axes in MATLAB and padding the second y-axis with zeros, you can use the following approach:

main.m
% Create sample data
x = 1:5;
y1 = [1 2 3 4 5];
y2 = [6 7 8 9 10];

% Create bar plot with first y-axis
bar(x, y1)

% Add second y-axis
ax2 = gca;
ax2.YAxis(2) = ylabel('y2');
ax2.YColor = 'r';
set(ax2, 'YLim', [0 max(y2)+2]);

% Pad the second y-axis with zeros
ax2_pos = ax2.Position;
ax1_pos = ax2_pos + [0 ax2_pos(4) 0 0];
ax1 = axes('Position',ax1_pos);
ax1.Color = 'none';
ax1.YAxis.Visible = 'off';
ax1.XAxis.Color = 'none';
ax1.XAxis.Visible = 'off';
ax1.YLim = [0 max(y2)+2];
ax1.YTick = [0 max(y2)];

% Plot zeros on the second y-axis
hold on
bar(x, zeros(size(x)), 'FaceColor', 'none')
hold off

% Adjust figure settings
xlabel('x')
ylabel('y1')
legend('y1')
title('Bar Plot with Two Y-Axes')
704 chars
36 lines

This code creates a bar plot with two y-axes. The first y-axis (left side) corresponds to the values in y1, and the second y-axis (right side) corresponds to the values in y2. The second y-axis is padded with zeros using an additional set of axes.

Note that in this example, the sample data is provided as x, y1, and y2. You can modify these variables to suit your specific data.

Hope this helps!

gistlibby LogSnag