Histogram bin location to place text for categorical data
Show older comments
Hello,
I'm trying to find the bin location for categorical data for histogram. Using text I can place the number of the counts for each bin like the following example:
C = categorical(X,1:1:length(categorical_edges_x),categorical_edges_x);
h1=histogram(C);
xloc = h1.BinEdges ;
yloc = h1.Values ;
text(xloc(1:end-1),yloc,num2str(yloc'),'vert','bottom','horiz','center');
The issue is that it doesn't like it when it is categorical, and it returns the following error:
Unrecognized method, property, or field 'BinEdges' for class 'matlab.graphics.chart.primitive.categorical.Histogram'.
Any suggestions?
1 Comment
Jonas
on 20 Jul 2022
try
double(xticks())
to see the xvalues
Accepted Answer
More Answers (1)
Since you x-data are categorical, you're working with a categorical ruler. This makes it difficult to position text at numeric x-values.
Option 1: don't use categorical data
Produce the histogram using your numeric data and then apply x-tick labels with your category names. You can do this with bar too if you want to keep the gap between cateogries. This will create a numeric xruler and you can position text anywhere along the x-axis.
Option 2: Place your labels along the cateogory values
@Voss provided a nice example of this in the other answer on this page. You could also place the text at the bottom of the bars in white font color, to suggest another style.
Option 3: Add a second row of tick labels in a categorical ruler
If you'd rather use cateogrical values and you want the labels to be at the bottom of the axes but not overlapping the categorical names
A = [1 3 3; 2 1 3; 1 1 2];
values = [1,2,3];
categoryNames = {'red' 'green' 'blue'};
C = categorical(A,values,categoryNames);
h1 = histogram(C);
ax = ancestor(h1,'axes');
tickValues = vertcat(ax.XTickLabel', num2cell(values));
newTickLabels = sprintf('%s\\newline%.0f\n',tickValues{:});
ax.XTickLabel = newTickLabels;
Categories
Find more on Histograms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
