Categorical Bar Plot keeps old categories
9 views (last 30 days)
I make a bar plot with categorical x-values as follows:
- define legend names (that will be the labels for each bar in the bar graph) depending on if the value is normal or lowered (specificity to the app I am writing)
- make the legend names categorical
- plot them together with the heights
- add text labels
app.legendnames = strings(app.n,1);
for i = 1:app.n
app.legendnames(i) = strcat("P",num2str(i),"-lowered");
else %remaining plank
app.legendnames(i) = strcat('P',num2str(i));
app.bx = reordercats(categorical(app.legendnames),app.legendnames);
app.by = heights;
b = bar(app.UIAxes, app.bx, app.by,0.5);
xtips = b(1).XEndPoints;
ytips = b(1).YEndPoints;
labels = compose("%6.0f",b(1).YData);
It looks like this
Now, when I call this plotting function again (without closing the app), each of these steps is called again. In this case, I adapt loweringHeights(2). In some way Matlab/App Designer keeps old labels that are now not anymore in use. These old labels are not part of the legendnames anymore. I know this because in other plots, the legendnames are plotted correctly. It is only in the bar graphs that I have this problem:
So I suspect the categorical thing is keeping old categories even when they are not anymore part of the new app.legendnames vector. I have no idea how to eliminate those old values. I was thinking about using removecats() but I don't see how I can tell what categories to eliminate. Any suggestions?
Cris LaPierre on 9 Nov 2021
That is the expected behavior of the categorical datatype. The list of possible categories is maintained, even if they are not present in the captured data. When creating a bar plot, the possible category names are used for X.
To get the behavior you want, use removecats to remove categories that are empty before plotting.