Clear Filters
Clear Filters

How to label X-axis on bar graph?

377 views (last 30 days)
Struggling in MATLAB
Struggling in MATLAB on 9 Oct 2022
Edited: dpb on 14 Oct 2022
I want to label a bar graph with a string array. I am using this following piece of code to label them. But it can not convert catStrArray yo categorical.
catStrArray = {'Baseline',splitlines(sprintf('Food deprivation%c(Week1)',newline)), ...
splitlines(sprintf('Food deprivation%c(Week2)',newline)),splitlines(sprintf('Food deprivation%c(Week3)',newline))};
label = categorical(catStrArray);
label = reordercats(label,catStrArray);
If I drop 'splitlines' as follows then I am not getting newline as intended.
catStrArray = {'Baseline',sprintf('Food deprivation%c(Week1)',newline), ...
sprintf('Food deprivation%c(Week2)',newline),sprintf('Food deprivation%c(Week3)',newline)};
What could I change in the code to make it work? I am looking for something like the following.
I have attached the barGraph code for reference.

Accepted Answer

dpb on 9 Oct 2022
Edited: dpb on 9 Oct 2022
cats=categorical(["Baseline";compose('Food deprivation(Week%d)',[1:3].')]);
The problem you ran into was not building a column vector of strings; note the .' transpose operator on the [1:3] vector above to make sure had a column vector. Otherwise, character or cell strings are simply catenated when strung together in a row.
It's a very long label for tick labels, though, but I don't think you can embed the \n character in a categorical variable to be interpreted as a newline by the TeX interpreter on labels; you could manage that with xticklabels and building strings to write.
Instead, I'd probably just put the 'Baseline' and 'Week N' on the tick labels and use the xlabel for the rest something like...
cats=categorical(["Baseline";compose('Week %d',[1:3].')]);
xlabel('Fasting Period')
ylabel('Food deprivation Effect')
dpb on 14 Oct 2022
Edited: dpb on 14 Oct 2022
cats=categorical(["Baseline";compose(['Food Dep\\newline Week %d'],[1:3].')]);
I wasn't thinking before; you don't bury the actual \n in the string but the TeX \newline directive for interpretation to display multiline labels; hence the concern about embedding control characters inside a categorical variable doesn't come into play.
Struggling in MATLAB
Struggling in MATLAB on 14 Oct 2022
Excellent! That worked. Thank you very much!

Sign in to comment.

More Answers (0)


Find more on MATLAB 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!