Categorical Bar Plot keeps old categories

12 次查看(过去 30 天)
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
if app.loweringHeights(i)
app.legendnames(i) = strcat("P",num2str(i),"-lowered");
else %remaining plank
app.legendnames(i) = strcat('P',num2str(i));
end
end
app.bx = reordercats(categorical(app.legendnames),app.legendnames);
app.by = heights;
cla(app.UIAxes);
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);
text(app.UIAxes, xtips,ytips,labels,'HorizontalAlignment','center','VerticalAlignment','bottom')
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?

回答(1 个)

Cris LaPierre
Cris LaPierre 2021-11-9
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.
  8 个评论
Simon Allosserie
Simon Allosserie 2021-11-10
Hi Chris, I tried this. It is indeed effective in the editor. Again, it is not effective in the app environment.
So I focussed on the difference, which is the axis handle in the app. What finally did the trick was
cla(app.UIAxes, 'reset');
so it seems some information about categorical bx was kept within the UIAxes environment.
Cris LaPierre
Cris LaPierre 2021-11-10
I see. Yes, it appears a uiaxes is combining the categories from the previous bar plot and the current one. I can't say if that is intentional or not, but it is different behavior than what happens in a figure axes. I believe your workaround is the best solution currently (R2021b).

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Categorical Arrays 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by