Matlab: Missing labels in bar chart

末鹿安然 提交于 2019-12-06 07:25:39

问题


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.


回答1:


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:

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.



来源:https://stackoverflow.com/questions/20439554/matlab-missing-labels-in-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!