Histogram bin location to place text for categorical data
19 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alessandro Maria Laspina
el 20 de Jul. de 2022
Respondida: Adam Danz
el 20 de Jul. de 2022
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 comentario
Respuesta aceptada
Voss
el 20 de Jul. de 2022
You can use h1.Categories instead of h1.BinEdges
% a guess at what your X and categorical_edges_x look like
categorical_edges_x = {'A' 'B' 'C' 'D' 'E'};
X = randi(numel(categorical_edges_x),10);
% make the categorical array
C = categorical(X,1:numel(categorical_edges_x),categorical_edges_x);
% make the histogram
h1=histogram(C);
% make the texts
xloc = 1:numel(h1.Categories);
yloc = h1.Values;
text(xloc,yloc,sprintfc('%d',yloc),'vert','bottom','horiz','center')
0 comentarios
Más respuestas (1)
Adam Danz
el 20 de Jul. de 2022
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;
0 comentarios
Ver también
Categorías
Más información sobre Data Distribution Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!