Automatic Adjusting of xticks depending of data

3 views (last 30 days)
Hey there,
I am using a bar plot to visualize data. However some of the y-values are empty and therefore shall not be visualized.
however the x-values for the barplot are categorical and i would like to delete those x-ticks which are linked with the empty y-values to clean up my plot.
How can i achieve that?

Accepted Answer

dpb
dpb on 21 Oct 2022
Edited: dpb on 21 Oct 2022
categorical axes are somewhat peculiar -- the categorical variable always contains all the categories for which it was created and there weren't missing values when the x variable was created; only the associated y value has some zero elements.
To not have those show up in the plot you'll need to create a new categorical variable that matches the wanted locations only--something like
isOK=~ismissing(y); % or y==0 or isfinite(y) or whatever is the actual condition to keep
cats=categories(x); % get the category names from the present x categorical array
xOK=categorical(x(isOK),x(isOK),cats(isOK)); % the new categorical variable to plot with
bar(xOK,y(isOK)) % will plot only the extant/wanted bars with names
Otherwise, you'll get a categorical axes with all categories in the original vector; even though the actual elements may not be shown/plotted, the axes will still be laid out in the original internal numerical position were when created.
categorical variables are kinda' tricky that way, they always carry around the entire definition of all categories in the original or augmented creation whether there are actual values for all categories or not; only the display names are not visible for the missing, but the categories are still defined. It's similar to datetime display formatting -- you can hide the normal display of any field such as the year, but the datetime value is still the same; only the display format has been changed.

More Answers (0)

Categories

Find more on Data Distribution Plots 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!