MATLAB: Bar plot (within a subplot) for unequally spaced X axis points

MATLABsubplot

I have the following code (I am including the plot for subplot (2,2,4)):
subplot(2,2,1);
subplot(2,2,2);
subplot(2,2,3);
subplot(2,2,4);
xIdx = [0.0,21.2,31.5,35.7,44.2,58.3,64.4,82.7,97.0,120.4];
b4 = bar(price_volatility,profit_all,'linewidth',0.1,'FaceColor','flat');
for k=1:size(profit_all,2)
b4(k).CData = k+1;
end
xticks([0.0 21.2 31.5 35.7 44.2 58.3 64.4 82.7 97.0 120.4]);
xticklabels({'0.0','21.2','31.5','35.7','44.2','58.3','64.4','82.7','97.0','120.4'});
xtickangle(45);
ax = gca;
ax.XAxis.FontSize = 8;
legend({'A1','A2'},'fontsize',9);
xlabel('Fig.2(d):X Axis Label','fontsize',12);
ylabel('Y Axis Label','fontsize',12);
I am getting a plot which doesn't look nice due to the unequal spacing on X axis. I would appreciate any suggestion to make it look better.

Best Answer

  1. Do not plot bar against xIdx, plot it against [1 2 3, ....]
  2. generate xticks (you can skip this step)
  3. convert xIdx to cell, and then to string, feed it to xticklabels
subplot(2,2,1);
subplot(2,2,2);
subplot(2,2,3);
subplot(2,2,4);
profit_all = 10+rand(1,10)*100;
xIdx = [0.0,21.2,31.5,35.7,44.2,58.3,64.4,82.7,97.0,120.4];
b4 = bar(profit_all,'linewidth',0.1,'FaceColor','flat');
for k=1:1
b4(k).CData = k+1;
end
xticks(1:length(profit_all));
% xticklabels({'0.0','21.2','31.5','35.7','44.2','58.3','64.4','82.7','97.0','120.4'});
xticklabels(cellfun(@num2str,num2cell(xIdx),'UniformOutput',false));
xtickangle(45);
ax = gca;
ax.XAxis.FontSize = 8;
% legend({'A1','A2'},'fontsize',9);
xlabel('Fig.2(d):X Axis Label','fontsize',12);
ylabel('Y Axis Label','fontsize',12);
Related Question