Search code examples
matlabhistogrammatlab-figurecategorical-data

Categorical histogram labels


I've created a categorical histogram :

h = histogram( categorical( emotions{startIndex:endIndex,:} ) )

h.Categories
ans =
  1×5 cell array
    {'ANGER'}    {'CONTEMPT'}    {'DISGUST'}    {'JOY'}    {'SADNESS'}

>> h.Values
ans =
   164    26    18   191     1

But there doesn't seem to be a way to display labels (i.e.h.Values) on the histogram bars. Following this post, I tried this:

text(h.Values, h.Categories, num2str(h.Values'), 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' );

but I just get:

Error using text First two or three arguments must be numeric doubles.

but the problem is my x values are never going to be numeric, they're categorical. How to fix it?


For a reproducible example, this would do:

emotions = { 'JOY','JOY','JOY','JOY','JOY','JOY','JOY','JOY','JOY','JOY','ANGER','ANGER','CONTEMPT','CONTEMPT','CONTEMPT','JOY','ANGER','ANGER','ANGER','ANGER'}
emotions = emotions.';
t = cell2table(emotions)
histogram(categorical(emotions))

Solution

  • You have interchanged the first two input arguments of text and h.Categories is not numeric double which it needs to be (as the error message is suggesting you).
    So the solution is:

    emotions = {'JOY','JOY','JOY','JOY','JOY','JOY','JOY','JOY','JOY', ...
         'JOY','ANGER','ANGER','CONTEMPT','CONTEMPT','CONTEMPT','JOY', ...
         'ANGER','ANGER','ANGER','ANGER'};
    % emotions = emotions.';    %No need of this line
    % t = cell2table(emotions); %No need of this line
    h = histogram(categorical(emotions));
    
    text(1:numel(h.Values), h.Values, num2str(h.Values.'), ...
        'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom');
    

    Result:

    output