Question

With Matlab 2012 and 2013, I found that setting XTickLabel on a bar chart only works with up to 15 bars. If there are more bars, labels are missing, as shown below.

Plotting 15 bars:

N = 15;
x = 1:N;
labels = num2str(x', '%d');
bar(x);
set(gca, 'XTickLabel', labels);

N = 15

Plotting 16 bars:

N = 16;
x = 1:N;
labels = num2str(x', '%d');
bar(x);
set(gca, 'XTickLabel', labels);

N = 16

For N > 15, it will always only display 10 labels.

Does anyone else experience this? Any work-arounds? I need all labels because I am plotting discrete categories and not a continuous function.

Was it helpful?

Solution

This happens because the tick labels have to match the ticks themselves. In the example you gave with N = 16; and x = 1:N;, MATLAB automatically makes the following XTicks (on your and my machines, at least):

>> xticks = get(gca,'xtick')
xticks =
     0     2     4     6     8    10    12    14    16    18
>> numel(xticks)
ans =
    10

Just 10 ticks for the 16 different bars. Thus, when you run set(gca, 'XTickLabel', labels); with labels = num2str(x', '%d'); (16 labels), it gives the second figure you showed with the wrong labels and ticks before/after the bars (at positions 0 and 18).

To set a tick label for each bar, you also need to set the ticks to match:

set(gca,'XTick',x) % this alone should be enough
set(gca,'XTickLabel',labels);

Then you will get the desired result:

enter image description here

For whatever reason, 16 seems to be the magic number at which MathWorks decided XTicks should not be drawn for each bar, leaving it up to the user to set them if needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top