I'm creating a bar plot in Matlab 2014b and would like to center the x-axis labels in between the tick marks. For example, in the following graph, the bars are correctly segmented by year using datetick and a slight adjustment I make. However, I would like the labels to appear half way in between the tick marks that are currently specified.
clear; close all;
a = rand(12, 1)-0.1;
x = linspace(datenum('03-31-2012'), datenum('12-31-2014'), 12);
b1 = bar(x, a);
datetick('x', 'yyyy');
display(datestr(x))
ax1 = gca;
bGapWidth = (x(2)-x(1));
bWidth = b1.BarWidth;
ax1.XLim = [x(1)-bGapWidth*bWidth x(end)+bGapWidth*bWidth];
initTick = ax1.XTick;
ax1.XTick = initTick + (bWidth*bGapWidth)/2 + (bGapWidth*(1-bWidth)/2);
I've seen a few similar questions but nothing quite the same. I've also seen suggestions of creating a dummy axis (one for labels, one for tick marks), but I've had some trouble here too - simply setting a new variable equal to the current axes object and making modifications changes the whole plot. Feel free to help me out on this part, or suggest a better solution in general.
1 Answer 1
clear; close all;
a = rand(12, 1)-0.1;
x = linspace(datenum('03-31-2012'), datenum('12-31-2014'), 12);
b1 = bar(x, a);
datetick('x', 'yyyy');
display(datestr(x))
h1=get(gca,'XTick');
h2=get(gca,'XTickLabel');
h3=length(h1);
xdiff=h1(2)-h1(1); % assuming uniform step interval in x-axis
h1=h1+0.4*xdiff; % this factor of 0.4 can be adjusted
ylim([0 1]);
for i=1:h3-1
text(h1(i),-0.05,num2str(h2(i,:)));
end
% instead of -0.05 relative to y put the labels where you like
set(gca,'XTickLabel',{});