Subsetting variables in bar function gives a zero for excluded x-values.
Show older comments
When subsetting variables within the bar function, the subsetting only works for the y values, and not for the x values. Here is an MRE of the issue:
x = categorical({'a','b','c'});
y = 1:3;
bar(x,y) % works just fine
bar(x(1:2),y(1:2)) % c shouldn't be there
The x value corresponding to 'c' should not appear, right? My goal is to have a bar plot without the 'c' value. Assigning the subset to a different variable, e.g. temp = x(1:2); does not work. In my code, I can't just do the equivalent of x=1:2; since I need to subset from a variable containing names. Thanks!
1 Comment
"The x value corresponding to 'c' should not appear, right?"
It definitely should appear, that is rather the point of catgorial arrays. Consider a simpler (rather contrived) example of two values TRUE and FALSE. If one way our data only happens to contain FALSE values, that does not change the range of possible values, which remains unchanged (as TRUE and FALSE). The possible values is not changed by what values actually occur in any specific data set: literally the categories remain unchanged.
If I want to plot several plots of a categorical array, then I want my independent axes to be the same in all cases.
Accepted Answer
More Answers (1)
I'm not sure this is the best way (in fact I'm pretty sure it's not), but it seems to do the job:
x = categorical({'a','b','c'});
y = 1:3;
c = categories(x)
xx = setcats(x,c(1:2))
% xx = removecats(x,c(3)) % appears to have the same effect
display(categories(xx));
figure();
bar(xx,y); % note that we still pass all elements of y in to bar()
3 Comments
Alex
on 20 Dec 2021
Voss
on 20 Dec 2021
I agree, it seems like there would be a way to completely remove categories from a categorical array. I never use categorical arrays so I don't know, but I figured out this method that seems to do the trick (whether it's the 'correct' way or not), so I figured I'd go ahead and post it so you can move forward with your project.
I'd be interested to see how people with more experience in categorical arrays would do this.
"it seems like there would be a way to completely remove categories from a categorical array"
The MATLAB approach: https://www.mathworks.com/help/matlab/ref/categorical.removecats.html
x = categorical({'a','c','a'}, {'a','b','c'});
categories(x)
x = removecats(x);
categories(x)
Categories
Find more on Annotations 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!



