Matlab: Missing labels in bar chart

bar-chart, charts, diagram, matlab

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 `XTick`s (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:

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

Problem

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); ``` Plotting 16 bars: ``` N = 16; x = 1:N; labels = num2str(x', '%d'); bar(x); set(gca, 'XTickLabel', labels); ``` 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.

Original source